MSDN Library

Get Keyword Suggestions in Java

The following example shows how to get keyword suggestions that could perform better than the specified keywords using the Ad Intelligence SuggestKeywordsFromExistingKeywords 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 GetKeywordsFromKeywords
//

import java.rmi.*;
import bingads.adintelligence.adapi.*;
import bingads.adintelligence.*;
import bingads.adintelligence.datacontracts.*;

/**
 *
 */
public class GetKeywordsFromKeywords {

    private static String namespace = null;
    private static BasicHttpBinding_IAdIntelligenceServiceStub service = null;

    // Specify your credentials.

    private static String m_password = "<passwordgoeshere>";
    private static String m_username = "<usernamegoeshere>";
    private static String m_token = "<devtokengoeshere>";

    // Specify the advertiser's account ID.

    private static long m_accountId = <accountidgoeshere>;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        AdIntelligenceServiceLocator locator = null;
        KeywordSuggestion[] suggestedKeywords = null;

        try
        {
            locator = new AdIntelligenceServiceLocator();
            namespace = locator.getServiceName().getNamespaceURI();
            service = (BasicHttpBinding_IAdIntelligenceServiceStub) locator.getBasicHttpBinding_IAdIntelligenceService();

            suggestedKeywords = GetSuggestedKeywords(m_accountId);

            if (suggestedKeywords != null)
            {
                for (KeywordSuggestion keyword : suggestedKeywords)
                {
                    if (null != keyword)
                    {
                        System.out.println(keyword.getKeyword());

                        if (null == keyword.getSuggestionsAndConfidence())
                        {
                            System.out.println("  There are no suggestions for the keyword.");
                        }
                        else
                        {
                            for (KeywordAndConfidence suggestion : keyword.getSuggestionsAndConfidence())
                            {
                                System.out.printf("  %s (%.2f%%)\n",
                                        suggestion.getSuggestedKeyword(),
                                        suggestion.getConfidenceScore() * 100);
                            }
                        }

                        System.out.println();
                    }
                }
            }
        }
        catch (RemoteException e)
        {
            if (new AdApiFaultDetail().getClass() == e.getClass() ||
                new ApiFaultDetail().getClass() == e.getClass())
            {
                ; // Ignore because we already caught these below.
            }
            else
            {
                System.out.print("Service communication error encountered: ");
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        catch (Exception e)
        {
            System.out.print("Error encountered: ");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Get the suggested keywords for each keyword specified in the request. The suggestion
     * type specifies the type of provider to use to generate the suggestions. For information
     * about the language and country combinations that each provider supports, see the
     * documentation on MSDN.
     */

    public static KeywordSuggestion[] GetSuggestedKeywords(long accountId) throws RemoteException
    {
        SuggestKeywordsFromExistingKeywordsRequest request = new SuggestKeywordsFromExistingKeywordsRequest();
        SuggestKeywordsFromExistingKeywordsResponse response = null;

        // Set the header properties.

        service.clearHeaders();
        service.setHeader(namespace, "DeveloperToken", m_token);
        service.setHeader(namespace, "UserName", m_username);
        service.setHeader(namespace, "Password", m_password);
        service.setHeader(namespace, "CustomerAccountId", m_accountId);

        // Specify request information.

        request.setKeywords(new String[] { "flower delivery" });
        request.setLanguage("English");
        request.setPublisherCountries(new String[] { "US", "CA" });
        request.setMaxSuggestionsPerKeyword(10);
        request.setSuggestionType(2); // Return keywords from other ad groups that include the specified keyword.

        try
        {
            response = service.suggestKeywordsFromExistingKeywords(request);
        }
        catch (AdApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("suggestKeywordsFromExistingKeywords failed with the following faults:");

            for (AdApiError error : fault.getErrors())
            {
                if (105 == error.getCode()) //  InvalidCredentials
                {
                    System.out.println("The specified credentials are not valid or the account is inactive.");
                }
                else
                {
                    System.out.print("\tError code: " + error.getErrorCode());
                    System.out.println(" (" + error.getCode() + ")");
                    System.out.println("\tMessage: " + error.getMessage());
                    System.out.println("\tDetail: " + error.getDetail());
                }
            }

            throw fault;  // To be caught and ignored in main.
        }
        catch (ApiFaultDetail fault)
        {
            // Log this fault.

            System.out.println("suggestKeywordsFromExistingKeywords failed with the following faults:");

            for (OperationError error : fault.getOperationErrors())
            {
                switch (error.getCode())
                {
                    case 106: //  UserIsNotAuthorized
                        System.out.println("The user is not authorized to call this operation.");
                        break;

                    case 1505: // CampaignServiceKeywordsArrayShouldNotBeNullOrEmpty
                        System.out.println("The list of keywords cannot be null or empty.");
                        break;

                    case 3407: // CampaignServiceInvalidMaxSuggestionsPerKeyword
                        System.out.println("The specified maximum number of suggestions to return per keyword is not valid.");
                        break;

                    case 3408: // CampaignServiceLanguageAndCountryNotSupported
                        System.out.println("One or more of the specified publisher countries is not allowed for the specified language.");
                        break;

                    case 3412: // CampaignServiceInvalidLanguage
                        System.out.println("The specified language is not valid.");
                        break;

                    case 3413: // CampaignServiceInvalidPublisherCountry
                        System.out.println("One or more of the specified publisher countries is not valid.");
                        break;

                    case 3420: // CampaignServiceInvalidSuggestionType
                        System.out.println("The specified suggestion type is not valid.");
                        break;

                    case 3421: // CampaignServiceUnSupportedCountryForSuggestionType
                        System.out.println("One or more of the specified publisher counties is not allowed for the specified suggestion type.");
                        break;

                    default:
                        System.out.print("\tError code: " + error.getErrorCode());
                        System.out.println(" (" + error.getCode() + ")");
                        System.out.println("\tMessage: " + error.getMessage());
                        System.out.println("\tDetail: " + error.getDetails());
                        break;
                }
            }

            for (BatchError error : fault.getBatchErrors())
            {
                System.out.print("\tError code: " + error.getErrorCode());
                System.out.println(" (" + error.getCode() + ")");
                System.out.println("\tIndex: " + error.getIndex());
                System.out.println("\tMessage: " + error.getMessage());
                System.out.println("\tDetail: " + error.getDetails());
            }

            throw fault;  // To be caught and ignored in main.
        }

        return response.getKeywordSuggestions();
    }
}

Community Additions

Show:
© 2016 Microsoft