The following code sample shows how to request and retrieve a keyword performance report by using Java.
// This example assumes that you are using Axis 1.4 and
// the Xerxes parser. Additionally, it requires
// precompiling the proxy classes by using wsdl2java.
// If you are using a different environment, update it as needed.
// Application-specific name of package.
// If you place this code in a package, invoke the code
// at the command prompt by typing
// java java_adCenter.MyReport
// along with the parameters used for the credentials and developer token.
// If you choose to not place this code in a package, invoke the code
// at the command prompt by typing
// java MyReport
// along with the parameters used for the credentials and developer token.
package java_adCenter;
import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import com.microsoft.adcenter.api.advertiser.v5.*;
public class MyReport
{
public static void main(String[] args)
{
int[] accountIds = { 489 }; // Application-specific value.
// The Microsoft adCenter API namespace,
// which is used in the SOAP header.
String namespace =
"https://adcenter.microsoft.com/api/advertiser/v5";
// This example URL is for the sandbox environment.
// Update the URL as needed when using the production environment.
String url = "https://sandboxapi.adcenter.microsoft.com/Api/Advertiser/V5.1/Reporting/ReportingService.svc?wsdl";
// The following is the production environment URL.
// String url = "https://adcenterapi.microsoft.com/Api/Advertiser/V5.1/Reporting/ReportingService.svc?wsdl";
IReportingService reportManagement = null;
ReportingServiceLocator reportServiceLocator = null;
BasicHttpBinding_IReportingServiceStub stub = null;
QueueReportRequest queueReportRequest = null;
QueueReportResponse queueReportResponse = null;
GetReportStatusRequest getReportStatusRequest = null;
GetReportStatusResponse getReportStatusResponse = null;
ReportRequestStatus reportRequestStatus = null;
ReportRequestStatusType status = null;
String reportId = null;
UserCredentials userCredentials = null;
ApplicationToken appToken = null;
DeveloperToken devToken = null;
try
{
if (args.length != 3)
{
// This application expects the user name, password, and
// developer token to be passed in as command-line arguments.
System.out.println("Correct usage:");
System.out.print("java MyReport ");
System.out.println("user_name password developertoken");
System.exit(-1);
}
reportServiceLocator = new
ReportingServiceLocator();
reportServiceLocator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
reportManagement =
reportServiceLocator.getBasicHttpBinding_IReportingService();
userCredentials = new UserCredentials();
devToken = new DeveloperToken();
appToken = new ApplicationToken();
// Assign values for the developer token and credentials.
// args[0] is the user name.
// args[1] is the password.
// args[2] is the developer token.
// The application token is reserved for future use and
// does not need to be assigned a value.
userCredentials.setUsername(args[0]);
userCredentials.setPassword(args[1]);
devToken.setValue(args[2]);
appToken.setValue(null);
stub = (BasicHttpBinding_IReportingServiceStub)
reportManagement;
// Assign the necessary values to the header.
stub.setHeader(namespace,
"ApplicationToken", appToken);
stub.setHeader(namespace,
"DeveloperToken", devToken);
stub.setHeader(namespace,
"UserCredentials", userCredentials);
// Create and initialize the keyword performance report request
// object.
KeywordPerformanceReportRequest reportRequest =
new KeywordPerformanceReportRequest();
// Specify the language of the report.
reportRequest.setLanguage(ReportLanguage.English);
// Specify the format of the report.
reportRequest.setFormat(ReportFormat.Xml);
reportRequest.setReturnOnlyCompleteData(false);
reportRequest.setReportName("My Keyword Report");
reportRequest.setAggregation(ReportAggregation.Monthly);
// Specify the time frame of the report.
ReportTime reportTime=new ReportTime();
reportTime.setPredefinedTime(ReportTimePeriod.LastSixMonths);
reportTime.setCustomDates(null);
reportTime.setCustomDateRangeStart(null);
reportTime.setCustomDateRangeEnd(null);
reportRequest.setTime(reportTime);
// Specify the scope of the report. This example goes
// only to the account level, but you can request a report
// for any number of accounts, ad groups, and campaigns.
AccountThroughAdGroupReportScope scope =
new AccountThroughAdGroupReportScope();
scope.setAccountIds(accountIds);
reportRequest.setScope(scope);
// Specify the filter for the report. The report request
// in this example specifies only the search ads that were
// displayed in the United States.
KeywordPerformanceReportFilter filter =
new KeywordPerformanceReportFilter();
String[] adDist = { "Search" };
filter.setAdDistribution(adDist);
String[] langAndRegion = { "UnitedStates" };
filter.setLanguageAndRegion(langAndRegion);
filter.setDeliveredMatchType(null);
filter.setKeywords(null);
reportRequest.setFilter(filter);
// Specify the columns that will be in the report.
KeywordPerformanceReportColumn[] columns;
columns = new KeywordPerformanceReportColumn[6];
columns[0] = KeywordPerformanceReportColumn.AccountName;
columns[1] = KeywordPerformanceReportColumn.CampaignName;
columns[2] = KeywordPerformanceReportColumn.Keyword;
columns[3] = KeywordPerformanceReportColumn.TimePeriod;
columns[4] = KeywordPerformanceReportColumn.Impressions;
columns[5] = KeywordPerformanceReportColumn.Conversions;
reportRequest.setColumns(columns);
// Create the service operation request object, and assign values.
queueReportRequest = new QueueReportRequest();
queueReportRequest.setReportRequest(reportRequest);
// Make the call to queue the report.
System.out.println(
"Calling ReportManagement.QueueReport");
queueReportResponse =
reportManagement.queueReport(queueReportRequest);
// Display the ApiCallTrackingData that was returned in
// the response header.
System.out.println("Successful QueueReport call.");
System.out.println(
"ApiCallTrackingData output from response header:");
System.out.println(
stub.getResponseHeader
(
namespace,
"ApiCallTrackingData")
);
System.out.println(); // A blank line to separate the text
// that follows.
reportId = queueReportResponse.getReportRequestId();
System.out.print("ReportRequestId: ");
System.out.println(reportId);
// Poll to get the status of the report until it is complete.
int waitMinutes = 15;
int maxWaitMinutes = 120;
int elapsedMinutes = 0;
do
{
// Wait the specified number of minutes before you poll.
System.out.print(String.format(
"Waiting another %d minutes. ",
waitMinutes));
System.out.println(String.format(
"Total wait time so far is %d minutes.",
elapsedMinutes));
Thread.sleep(waitMinutes * 60 * 1000);
elapsedMinutes += waitMinutes;
getReportStatusRequest = new GetReportStatusRequest();
getReportStatusRequest.setReportRequestId(reportId);
// Make the call to get the report status.
System.out.println(
"Calling ReportManagement.GetReportStatus");
getReportStatusResponse =
reportManagement.getReportStatus(getReportStatusRequest);
// Display the ApiCallTrackingData returned
// in the response header.
System.out.println("Successful GetReportStatus call.");
System.out.println(
"ApiCallTrackingData output from response header:");
System.out.println(
stub.getResponseHeader
(
namespace,
"ApiCallTrackingData")
);
System.out.println(); // A blank line to separate the text
// that follows.
reportRequestStatus =
getReportStatusResponse.getReportRequestStatus();
status = reportRequestStatus.getStatus();
// If the report was created, download it.
if (ReportRequestStatusType.Success == status)
{
String fileName = null;
String downloadURLString = null;
URL downloadUrl = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
int count = 0;
fileName = reportId + ".zip";
// Open a connection to the URL where
// the report is available.
downloadURLString =
reportRequestStatus.getReportDownloadUrl();
downloadUrl = new URL(downloadURLString);
inputStream = downloadUrl.openStream();
// Open the report file.
fileOutputStream = new FileOutputStream(fileName);
// Read the report data.
while (-1 != (count = inputStream.read()))
{
// Write the report data to the file.
fileOutputStream.write(count);
}
// Flush and close the file.
fileOutputStream.flush();
fileOutputStream.close();
System.out.println(String.format(
"The report named %s was successfully downloaded.",
fileName));
break;
}
else if (ReportRequestStatusType.Pending == status)
{
// The report is not yet ready.
continue;
}
else
{
// An error occurred.
throw new Exception(status.toString());
}
} while (elapsedMinutes < maxWaitMinutes);
}
// Exception handling.
// Capture adCenter API exceptions.
catch (ApiFaultDetail fault)
{
System.out.println("ApiFaultDetail exception encountered!");
System.out.println(String.format("Tracking ID: %s",
fault.getTrackingId()));
// Display any service operation error information.
for (int i = 0; i < fault.getOperationErrors().length; i++)
{
System.out.println("Operation error encountered:");
System.out.println(String.format("\tCode: %s",
fault.getOperationErrors()[i].getCode()));
System.out.println(String.format("\tMessage: %s",
fault.getOperationErrors()[i].getMessage()));
}
// Exit the application or take other action.
System.exit(-1);
}
// Capture exceptions on the client that are unrelated to
// adCenter API.
catch (Exception e)
{
System.out.print("Error encountered: ");
e.printStackTrace();
// Exit the application or take other action.
System.exit(-1);
}
}
}