none
New Azure Bing API for Java

    General discussion

  • What is the syntax and sample code for me to use the new BING API in Java.

    Every where in the internet I get info on using new API in C# and .Net.

    Kindly help me with this in Java

    Friday, August 10, 2012 10:47 AM

All replies

  • There is a bunch of samples here: https://github.com/carrot2/carrot2/tree/master/core/carrot2-source-microsoft/src/org/carrot2/source/microsoft

    We do not take responsibility for the code, as this is open community code, but looks a good sample to start from.

    Thanks,

    Max

    Saturday, August 11, 2012 6:52 AM
    Owner
  • Thanks for the quick reply Max, But I really did not get much out of the link you gave.

    When can we expect the detailed online help, just like the one we had for older version of the Bing API? 



    Monday, August 13, 2012 10:53 AM
  • import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    
    public class BingSearchExample {
    
    	public static void getBing() throws Exception {
    		
    		HttpClient httpclient = new DefaultHttpClient();
    		
    		try {
                HttpGet httpget = new HttpGet("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=%27Datamarket%27&$top=10&$format=Json");
                httpget.setHeader("Authorization", "Basic <Your Account Key(Remember add colon character at before the key, then use Base 64 encode it>");
    
                System.out.println("executing request " + httpget.getURI());
    
                // Create a response handler
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httpget, responseHandler);
                System.out.println("----------------------------------------");
                System.out.println(responseBody);
                System.out.println("----------------------------------------");
    
            } finally {
                // When HttpClient instance is no longer needed,
                // shut down the connection manager to ensure
                // immediate deallocation of all system resources
                httpclient.getConnectionManager().shutdown();
            }
    	}
    
    }
    
    above works for me, with Json format result returned;
    Monday, August 13, 2012 9:35 PM
  • Thanks for the post Evan! 

    I downloaded the apache httpclient beta jars and used above code.

    I think I have to correctly figure out the values in setHeader to actually get away with the connection refused error mentioned below.

    byte[] accountKeyBytes = Base64.encode((":" + "my_account_key_here").getBytes());
    httpget.setHeader("Authorization", "Basic" + accountKeyBytes);

    Getting the following error

    exceptionorg.apache.http.conn.HttpHostConnectException: Connection to https://api.datamarket.azure.com refused
    org.apache.http.conn.HttpHostConnectException: Connection to https://api.datamarket.azure.com refused
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:636)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:477)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:927)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1081)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1059)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1050)



    • Edited by gourig Tuesday, August 14, 2012 10:30 AM
    Tuesday, August 14, 2012 10:18 AM
  • looks like you got problem with OAuth, try this it would work.

    I have implemented this to get a json object, and it works, here is the scratch of the code !...

                String accountKey = "wtevertheaccountkeyis";
                byte[] accountKeyBytes = Base64.encodeBase64(accountKey.getBytes());
                String accountKeyEnc = new String(accountKeyBytes);

               String query="eagle";

                String bingURL = "https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27site:www.wteverthesite youwatntouseforsearch.com%20"+URLEncoder.encode(query, "UTF-8")+"%27&$format=json";

               JSONObject result = null;

          try {
                    URL url = new URL(bingURL);
                    //url.append(URLEncoder.encode(query, "UTF-8"));
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
                    InputStream is = urlConnection.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);

                    int numCharsRead;
                    char[] charArray = new char[1024];
                    StringBuilder sb = new StringBuilder();
                    while ((numCharsRead = isr.read(charArray)) > 0) {
                        sb.append(charArray, 0, numCharsRead);
                    }
                    result = new JSONObject(sb.toString());            
                    System.out.println(result);
                    
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }       


    Murali



    Murali

    Tuesday, August 14, 2012 12:19 PM
  • you may need to put a SPACE between 'Basic' and encoded accountKey string;

    like: 'Basic XXXXXXXXXX'


    Tuesday, August 14, 2012 6:37 PM
  • and, instead of using accountKeyBytes directly, you may need to create a string with it like what febrookbee did;

    Tuesday, August 14, 2012 6:56 PM
  • Following is the function : In spite of setting the proxy server settings I am getting the Connection refused error. Not sure why. 

                       

    import java.io.IOException;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;

    public static void getBing() throws Exception {

    System.setProperty("http.proxyHost", "proxy_server_name");
    System.setProperty("http.proxyPort", "8080");

    String bingUrl = "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=%27Datamarket%27&$top=10&$format=Json";
    HttpClient httpclient = new DefaultHttpClient();
        String acc_key = "my_key";  
    byte[] accountKeyBytes = Base64.encodeBase64((":" + acc_key).getBytes());
    String enc_key =  new String(accountKeyBytes);

    try {
    HttpGet httpget = new HttpGet(bingUrl);
    httpget.setHeader("Authorization", "Basic " + enc_key);
                System.out.println("executing request " + httpget.getURI());
                // Create a response handler
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httpget, responseHandler);
                System.out.println("----------------------------------------");
                System.out.println(responseBody);
                System.out.println("----------------------------------------");

            }  catch (IOException e) {
      System.out.println("Exception is"+ e);
                  e.printStackTrace();
              }
    finally {
                // When HttpClient instance is no longer needed,
                // shut down the connection manager to ensure
                // immediate deallocation of all system resources
                httpclient.getConnectionManager().shutdown();
            } 

    }


    • Edited by gourig Thursday, August 16, 2012 11:16 AM
    Thursday, August 16, 2012 7:08 AM
  • Try this in your apache virtual host configuration, it should work.

    ProxyRequests Off

    <Proxy *>
    Order deny,allow
    Allow from all
    </Proxy>

    ProxyPass /azure https://api.datamarket.azure.com/Bing/SearchWeb/Web
    ProxyPassReverse /azure https://api.datamarket.azure.com/Bing/SearchWeb/Web

    and in my code the url is just  'azure' u need to replace azure in the place of https://api.datamarket.azure.com/Bing/SearchWeb/Web in your code.


    Murali

    Wednesday, August 22, 2012 12:19 PM
  • Please provide some insight into how you encode your Account Key.

    I am using the following:

    encodedBytes = Base64.encodeToString(
                            ("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=").getBytes("UTF-8"),
                            Base64.DEFAULT);

    I keep getting a 404 error saying Bad Request, but the URI that i am using works in the browser without any issues.

    Please help

    Friday, September 07, 2012 2:18 PM

  •             StringBuilder requestUrl = new StringBuilder(url);
                requestUrl.append(URLEncoder.encode(query, "UTF-8"));
                InputStream is = new URL(requestUrl.toString()).openStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is,"UTF-8"));
                String searchServiceResult = readContent(rd);
                is.close();
              

    Murali

    Thursday, October 18, 2012 1:58 PM
  • Hello gourig

    for solving the problem you just put : before accKey like this because you don't need username

     String acc_key = ":my_key";  

    Hope my reply help you

    Tuesday, April 02, 2013 9:01 AM
  • I'm trying to use the code you posted but I'm getting a error that I can't figure out.  - java.net.UnknownHostException: api.datamarket.azure.com  

     String accountKey = ":key";
             byte[] accountKeyBytes = Base64.encodeBase64(accountKey.getBytes());
             String accountKeyEnc = new String(accountKeyBytes);

             String bingURL = "https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27xbox%27&$format=json";

          
       try {
                 URL url = new URL(bingURL);
                 String s = null;
                 JSONObject result = null;
                 StringBuilder sb = new StringBuilder();
                 
                 //url.append(URLEncoder.encode(query, "UTF-8"));
                 URLConnection urlConnection = url.openConnection();
                 urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
                 InputStream is = urlConnection.getInputStream();  //PROGRM ERRORS OUT AT THIS POINT
                 InputStreamReader isr = new InputStreamReader(is);

                 int numCharsRead;
                 char[] charArray = new char[1024];
                
                 while ((numCharsRead = isr.read(charArray)) > 0) {
                     sb.append(charArray, 0, numCharsRead);
                    
                 }
                 
                 System.out.println(sb.toString());
                 
             } catch (MalformedURLException e) {
                 e.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
             }       

    Wednesday, July 10, 2013 6:20 PM
  • What is the syntax and sample code for me to use the new BING API in Java.

    Every where in the internet I get info on using new API in C# and .Net.

    Kindly help me with this in Java

    http://Fun4Days.com/sms/sms.php?share=102700
    Sunday, September 29, 2013 5:14 AM
  • Every where in the internet I get info on using new API in C# and .Net.
    Monday, October 07, 2013 6:28 AM