Add Ads in Java

The following example shows how to create ads within an ad group using the Campaign Management AddAds service operation.

This example has been developed and run within the environment described in Getting Started Using Java with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.


// Command line usage:
// java MyCreateAds username password developertoken
// 

import java.io.*;
import java.util.*;
import java.net.URL;
import bingads.campaignmanagement.*;
import bingads.campaignmanagement.adapi.*;
import bingads.campaignmanagement.datacontracts.*;

public class MyCreateAds
{
    public static void main(String[] args)
    {
        
        // Application-specific values.
        java.lang.Long accountId = new Long(<youraccountid>);
        java.lang.Long adGroupId = new Long(<youradgroupid>);

        // The Microsoft Bing Ads API namespace,
        // which is used in the SOAP header.
        String namespace = 
            "https://adcenter.microsoft.com/v8";

        // Update the URL as needed for the corresponding environment.
        // This example URL is for the sandbox environment.
        String url = "https://api.sandbox.bingads.microsoft.com/Api/Advertiser/v8/CampaignManagement/CampaignManagementService.svc?wsdl";
        // The following is the production environment URL.
        // String url = "https://adcenterapi.microsoft.com/Api/Advertiser/v8/CampaignManagement/CampaignManagementService.svc?wsdl";

        ICampaignManagementService campaignManagement = null;

        CampaignManagementServiceLocator campaignServiceLocator = null;

        BasicHttpBinding_ICampaignManagementServiceStub stub = null;

        AddAdsRequest addAdsRequest = null;
        AddAdsResponse addAdsResponse = null;

        Ad[] ads = null;
        
        // Two text ads and one mobile ad will be used in this example.
        TextAd textAd1 = null;
        TextAd textAd2 = null;
        MobileAd mobileAd = null;
        
        bingads.campaignmanagement.Date startDate = null, endDate = 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 MyCreateAds ");
                System.out.println("username password developertoken");
                System.exit(-1);
            }

            campaignServiceLocator = new
              CampaignManagementServiceLocator();

            campaignServiceLocator.setBasicHttpBinding_ICampaignManagementServiceEndpointAddress(url);

            campaignManagement =
             campaignServiceLocator.getBasicHttpBinding_ICampaignManagementService();

            stub = (BasicHttpBinding_ICampaignManagementServiceStub)
                          campaignManagement;

            // Assign values for the credentials and the developer token.
            // 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.

            stub.setHeader(namespace,
                     "ApplicationToken", "");
            stub.setHeader(namespace,
                     "DeveloperToken", args[2]);
            stub.setHeader(namespace,
                     "UserName", args[0]);
            stub.setHeader(namespace,
                     "Password", args[1]);
            stub.setHeader(namespace,
                     "CustomerAccountId", accountId);

            // This example creates three ads.
            ads = new Ad[3];

            // Initialize two text ad objects.
            textAd1 = new TextAd(); 
            textAd1.setTitle("Alpine Ski House");
            textAd1.setDestinationUrl("http://www.alpineskihouse.com");
            textAd1.setDisplayUrl("alpineskihouse.com");
            textAd1.setText("Alpine Ski House has a great ski selection for you.");

            textAd2 = new TextAd();
            textAd2.setTitle("Adventure Works");
            textAd2.setDestinationUrl("http://www.adventure-works.com");
            textAd2.setDisplayUrl("adventure-works.com");
            textAd2.setText("Adventure Works has a great selection for you.");

            // Initialize a mobile ad.
            mobileAd = new MobileAd();
            mobileAd.setTitle("Adventure Works");
            mobileAd.setDestinationUrl("http://www.adventure-works.com/mobile");
            mobileAd.setDisplayUrl("adventure-works.com");
            mobileAd.setText("Shop by phone now.");
            
            // Assign the initialized ads to the array.
            ads[0] = textAd1;
            ads[1] = textAd2;
            ads[2] = mobileAd;

            // Create the service operation request object, and then assign values.
            addAdsRequest = new AddAdsRequest();
            addAdsRequest.setAdGroupId(adGroupId);
            addAdsRequest.setAds(ads);
            
            // Make the call to add the ads.
            System.out.println(
                "Calling CampaignManagement.AddAds");
            addAdsResponse = 
                campaignManagement.addAds(addAdsRequest);
            
            // Display the TrackingId that was returned 
            // in the response header.
            System.out.println("Successful AddAds call.");
            System.out.println(
                "TrackingId output from response header:");
            System.out.println(
                 stub.getResponseHeader
                 (
                   namespace,
                   "TrackingId")
                 );

            // Insert a blank line to separate the text that follows.
            System.out.println();  

            // Display the IDs for the ads that were created.
            for (int i = 0; i < addAdsResponse.getAdIds().length; i++)
            {
                System.out.println(
                  String.format("Ad %s was added.",
                     addAdsResponse.getAdIds()[i]));
            }
        }

        // Exception handling.
        
        catch (EditorialApiFaultDetail fault)
        {
            System.out.println("EditorialApiFaultDetail exception encountered.");
            System.out.println(String.format("Tracking ID: %s",
                      fault.getTrackingId()));

            // Display editorial error information.
            for (int i = 0; i < fault.getEditorialErrors().length; i++)
            {
                System.out.println(String.format("Editorial validation error for item at array index %s.",
                        fault.getEditorialErrors()[i].getIndex()));
                System.out.println(String.format("\tMessage: %s",
                        fault.getEditorialErrors()[i].getMessage()));
                System.out.println(String.format("\tErrorCode: %s",                         
                        fault.getEditorialErrors()[i].getErrorCode()));
                System.out.println(String.format("\tFailed text: %s",
                        fault.getEditorialErrors()[i].getDisapprovedText()));
                System.out.println(String.format("\tCode: %s",                         
                        fault.getEditorialErrors()[i].getCode()));
            }
            
            // Display service operation error information.
            for (int i = 0; i < fault.getOperationErrors().length; i++)
            {
                System.out.println("Operation error encountered:");
                System.out.println(String.format("\tMessage: %s",
                        fault.getOperationErrors()[i].getMessage()));
                System.out.println(String.format("\tDetails: %s",
                        fault.getOperationErrors()[i].getDetails()));
                System.out.println(String.format("\tErrorCode: %s",
                        fault.getOperationErrors()[i].getErrorCode()));
                System.out.println(String.format("\tCode: %s",
                        fault.getOperationErrors()[i].getCode()));
            }

            // Display batch error information.
            for (int i = 0; i < fault.getBatchErrors().length; i++)
            {
                System.out.println(String.format("Batch error encountered for array index %s.",
                        fault.getBatchErrors()[i].getIndex()));
                System.out.println(String.format("\tMessage: %s",
                        fault.getBatchErrors()[i].getMessage()));
                System.out.println(String.format("\tDetails: %s",
                        fault.getBatchErrors()[i].getDetails()));
                System.out.println(String.format("\tErrorCode: %s",
                        fault.getBatchErrors()[i].getErrorCode()));
                System.out.println(String.format("\tCode: %s",
                        fault.getBatchErrors()[i].getCode()));
            }

            // Exit the application or take other action.
            System.exit(-1);
        }
        
        catch (AdApiFaultDetail fault)
        {
            System.out.println("AdApiFaultDetail exception encountered.");
            System.out.println(String.format("Tracking ID: %s",
                      fault.getTrackingId()));

            // Display API error information.
            for (int i = 0; i < fault.getErrors().length; i++)
            {
                System.out.println("Error encountered:");
                System.out.println(String.format("\tMessage: %s",
                        fault.getErrors()[i].getMessage()));
                System.out.println(String.format("\tDetail: %s",
                        fault.getErrors()[i].getDetail()));
                System.out.println(String.format("\tErrorCode: %s",
                        fault.getErrors()[i].getErrorCode()));
                System.out.println(String.format("\tCode: %s",
                        fault.getErrors()[i].getCode()));
            }

            // Exit the application or take other action.
            System.exit(-1);
        }

        // Capture exceptions on the client that are unrelated to
        // the Bing Ads API.
        catch (Exception e)
        {
            System.out.print("Error encountered: ");
            e.printStackTrace();
            
            // Exit the application or take other action.
            System.exit(-1);
        }

    }
}

Community Additions

Show: