演练:Java 中的必应广告 API Web 应用程序
此示例 Java Web 应用程序通过你提供的凭据提示用户同意,然后获取经过身份验证的用户可以访问的帐户。
必须首先注册应用程序,并记下客户端 ID (已注册的应用程序 ID) 、客户端机密 (注册的密码) 和重定向 URI。 有关注册应用程序和授权代码授予流的详细信息,请参阅 使用 OAuth 进行身份验证。
还需要生产 开发人员令牌。 可以按如下所述分步创建示例,也可以从 GitHub 下载更多示例。
注意
此示例演示了生产中的 OAuth 身份验证。 有关配置沙盒的信息,请参阅 配置沙盒。
Web 应用程序身份验证示例 Walk-Through
打开 Eclipse 开发环境。
通过 File -New ->Project ->>Maven ->Maven Project 创建新项目,然后单击“下一步”。
在“ 新建 Maven 项目 ”对话框中,确保未选中 “创建简单项目 (跳过原型选择) 选项,然后单击” 下一步”。 在下一步中,你将选择一个 Maven 原型。
在“ 新建 Maven 项目 ”对话框中,选择 Maven Web 应用原型,然后单击“ 下一步”。 组 ID 为 org.apache.maven.archetypes,项目 ID 为 maven-archetype-webapp。
在“ 新建 Maven 项目 ”对话框中,指定项目的项目参数,然后单击“ 完成”。 例如,可以将 组 ID 设置为 com.microsoft.bingads.examples, 将项目 ID 设置为 BingAdsWebApp。
如果所需的 javax servlet JAR 尚未在 Java 生成路径中,请将这些 JAR 添加到项目库。 在 “项目资源管理器”中,右键单击 BingAdsWebApp 项目,然后单击“ 属性”。 在“ 属性 ”对话框中,转到“ Java 生成路径 ->库 ”选项卡,单击“ 添加外部 JAR”,然后导航到 {EclipseInstallationPath}/plugins/ ,例如选择 javax.servlet.jsp_2.2.0.v20111201158 和 javax.servlet_3.0.0.v201112011016。
将 servlet JAR 包含在项目的顺序和导出的条目中。 在 “Java 生成路径 ->顺序和导出 ”选项卡中,单击“ 全 选 (至少选择 servlet JAR) ,然后单击” 完成”。
在项目的 Web 部署程序集中包含 servlet JAR。 在 “项目资源管理器”中,右键单击“BingAdsWebApp”项目,然后选择“ 属性”。 在 “属性 ”对话框中,转到“ 部署程序集 ->添加”,选择“ Java 生成路径条目”,然后单击“ 下一步”。 选择在前面的步骤中添加的所有 JAR,在“新建程序集指令”对话框中单击“完成”,然后在“属性”对话框中单击“应用”。
在 “项目资源管理器”中,右键单击 pom.xml 文件,然后选择“ 使用 ->文本编辑器打开”。 添加 com.microsoft.bingads 依赖项,如以下示例所示,并保存 pom.xml。
注意
有关最新 SDK 依赖项版本的详细信息,请参阅 必应广告 Java SDK GitHub README.md。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.microsoft.bingads.examples</groupId> <artifactId>BingAdsWebApp</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>BingAdsWebApp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.microsoft.bingads</groupId> <artifactId>microsoft.bingads</artifactId> <version>13.0.17</version> </dependency> </dependencies> <build> <finalName>BingAdsWebApp</finalName> </build> </project>
在 “项目资源管理器”中,右键单击 BingAdsWebApp 项目的“Web 内容”文件夹,然后选择“ 新建 ->JSP 文件”。 将文件命名为 index.jsp ,然后单击“ 完成”。
打开 Index.jsp 文件,并将其内容替换为以下代码块。 必须使用注册应用程序时预配的 ClientId、ClientSecret 和 RedirectionUri 编辑以下示例。 还需要使用生产 开发人员令牌编辑示例。 如果使用沙盒,则需要按照 配置沙盒中的步骤操作。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.net.URL" %> <%@ page import="com.microsoft.bingads.*" %> <%@ page import="com.microsoft.bingads.v13.customermanagement.*" %> <%! static AuthorizationData authorizationData; static ServiceClient<ICustomerManagementService> CustomerService; private static java.lang.String DeveloperToken = "<DeveloperTokenGoesHere>"; private static java.lang.String ClientId = "<ClientIdGoesHere>"; private static java.lang.String ClientSecret = "<ClientSecretGoesHere>"; private static java.lang.String RedirectUri = "<RedirectUriGoesHere>"; static long accountsCount = 0; %> <%! //Gets a User object by the specified Microsoft Advertising user identifier. static User getUser(java.lang.Long userId) throws Exception { GetUserRequest request = new GetUserRequest(); request.setUserId(userId); return CustomerService.getService().getUser(request).getUser(); } // Searches by UserId for accounts that the user can manage. static ArrayOfAdvertiserAccount searchAccountsByUserId(java.lang.Long userId) throws AdApiFaultDetail_Exception, ApiFault_Exception{ ArrayOfPredicate predicates = new ArrayOfPredicate(); Predicate predicate = new Predicate(); predicate.setField("UserId"); predicate.setOperator(PredicateOperator.EQUALS); predicate.setValue("" + userId); predicates.getPredicates().add(predicate); Paging paging = new Paging(); paging.setIndex(0); paging.setSize(10); final SearchAccountsRequest searchAccountsRequest = new SearchAccountsRequest(); searchAccountsRequest.setPredicates(predicates); searchAccountsRequest.setPageInfo(paging); return CustomerService.getService().searchAccounts(searchAccountsRequest).getAccounts(); } // Outputs the account and parent customer identifiers for the specified accounts. static void printAccounts(ArrayOfAdvertiserAccount accounts) throws Exception { for (Account account : accounts.getAccounts()) { System.out.printf("AccountId: %d\n", account.getId()); System.out.printf("CustomerId: %d\n", account.getParentCustomerId()); } } %> <% // Main execution try { OAuthWebAuthCodeGrant oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant( ClientId, ClientSecret, new URL(RedirectUri) ); oAuthWebAuthCodeGrant.setNewTokensListener(new NewOAuthTokensReceivedListener() { @Override public void onNewOAuthTokensReceived(OAuthTokens newTokens) { java.lang.String newAccessToken = newTokens.getAccessToken(); java.lang.String newRefreshToken = newTokens.getRefreshToken(); java.lang.String refreshTime = new java.text.SimpleDateFormat( "MM/dd/yyyy HH:mm:ss").format(new java.util.Date()); System.out.printf("Token refresh time: %s\n", refreshTime); System.out.printf("New access token: %s\n", newAccessToken); System.out.printf("You should securely store this new refresh token: %s\n", newRefreshToken); } }); if (authorizationData == null) { if (request.getParameter("code") == null) { URL authorizationUrl = oAuthWebAuthCodeGrant.getAuthorizationEndpoint(); response.sendRedirect(authorizationUrl.toString()); return; } else { OAuthTokens tokens = oAuthWebAuthCodeGrant.requestAccessAndRefreshTokens( new URL(request.getRequestURL() + "?" + request.getQueryString())); authorizationData = new AuthorizationData(); authorizationData.setDeveloperToken(DeveloperToken); authorizationData.setAuthentication(oAuthWebAuthCodeGrant); } } CustomerService = new ServiceClient<ICustomerManagementService>( authorizationData, ICustomerManagementService.class); User user = getUser(null); // Search for the accounts that the user can access. ArrayOfAdvertiserAccount accounts = searchAccountsByUserId(user.getId()); accountsCount = accounts.getAccounts().size(); System.out.println("The user can access the following Microsoft Advertising accounts: \n"); printAccounts(accounts); // Customer Management service operations can throw AdApiFaultDetail. } catch (AdApiFaultDetail_Exception ex) { System.out.println("The operation failed with the following faults:\n"); for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors()) { System.out.printf("AdApiError\n"); System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", error.getCode(), error.getErrorCode(), error.getMessage() ); } // Customer Management service operations can throw ApiFault. } catch (ApiFault_Exception ex) { System.out.println("The operation failed with the following faults:\n"); for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors()) { System.out.printf("OperationError\n"); System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage() ); } } catch (Exception ex) { // Ignore fault exceptions that we already caught. if (ex.getCause() instanceof AdApiFaultDetail_Exception || ex.getCause() instanceof ApiFault_Exception ) { ; } else { System.out.println("Error encountered: "); System.out.println(ex.getMessage()); ex.printStackTrace(); } } %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Microsoft Advertising Web Application Example</title> <link rel="stylesheet" href="styles/styles.css" type="text/css" media="screen"> </head> <body> <div id="content" class="container"> <div> <br/> <b>You have <%= accountsCount %> accounts</b> </div> </div> </body> </html>
应用程序已准备好部署到服务器。 例如,可以使用 Azure 应用服务发布 Web 应用。 有关详细信息,请参阅 部署 Web 应用程序。 启动应用程序时,系统会默认提示 Microsoft 帐户凭据在生产环境中进行身份验证。
部署 Web 应用程序
如果使用 Microsoft Azure 部署 Web 应用程序,则需要满足以下条件。
基于 Java 的 Web 服务器或应用程序服务器的分发,例如 Apache Tomcat、GlassFish、JBoss Application Server、Jetty 或 IBM® WebSphere® Application Server Liberty Core。
可以从 获取的 https://azure.microsoft.com/pricing/purchase-options/Azure 订阅。
(可选)可以安装 Microsoft Open Technologies) 的 Azure Toolkit for Eclipse (,并使用 Azure 云服务部署 Web 应用程序。 有关详细信息,请参阅 安装 Azure Toolkit for Eclipse。