Export (0) Print
Expand All

Get User Demographics in Java

The following example shows how to get the age and gender of users who have searched for specific keywords using the Ad Intelligence GetKeywordDemographics 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 GetDemographics
//

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

/**
 *
 */
public class GetDemographics {

    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;
        KeywordDemographicResult[] demographics = null;

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

            demographics = GetDemographics(m_accountId);

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

                    if (null == keyword.getDevice())
                    {
                        System.out.println("  There is no demographic data available for the keyword.\n");
                    }
                    else
                    {
                        System.out.println("  " + keyword.getDevice());
                        System.out.println("    Female: " + 
                                keyword.getKeywordDemographics().getFemale());
                        System.out.println("    Male: " + 
                                keyword.getKeywordDemographics().getMale());
                        System.out.println("    Ages 18 to 24: " + 
                                keyword.getKeywordDemographics().getAge18_24());
                        System.out.println("    Ages 25 to 34: " + 
                                keyword.getKeywordDemographics().getAge25_34());
                        System.out.println("    Ages 35 to 49: " + 
                                keyword.getKeywordDemographics().getAge35_49());
                        System.out.println("    Ages 50 to 64: " + 
                                keyword.getKeywordDemographics().getAge50_64());
                        System.out.println("    Over 64: " + 
                                keyword.getKeywordDemographics().getAge65Plus());
                        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 age and gender of users who have searched for the specified keywords.
     * The demographic information is broken out by device type.
     */

    public static KeywordDemographicResult[] GetDemographics(long accountId) throws RemoteException
    {
        GetKeywordDemographicsRequest request = new GetKeywordDemographicsRequest();
        GetKeywordDemographicsResponse 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.setDevice(new String[] { "Smartphones", "Computers", "NonSmartphones" });
        request.setLanguage("English");
        request.setPublisherCountry("US");

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

            System.out.println("getKeywordDemographics 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("getKeywordDemographics 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 1257: // CampaignServiceMissingLanguage
                        System.out.println("The language cannot be null or empty.");
                        break;

                    case 1505: // CampaignServiceKeywordsArrayShouldNotBeNullOrEmpty
                        System.out.println("The list of keywords cannot be null or empty.");
                        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 3417: //CampaignServiceInvalidDevice
                        System.out.println("One or more of the specified devices is not a valid device 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.getKeywordDemographicResult();
    }
}

Community Additions

Show:
© 2014 Microsoft