How can I authenticate in Java to use the new bing search api from Azure Marketplace?The migration guide does not provide you with info about Java
Asked
Active
Viewed 4,623 times
1 Answers
8
You'll need to encode your accountKey to Base64 and pass it to each request using the Authorization header.
String bingUrl = "https://api.datamarket.azure.com/Bing/Search/................";
String accountKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url = new URL(bingUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
...
This code is based on the the PHP example found in the Migrating to the Bing Search API in Windows Azure Marketplace document.
Update: Modified the encodeBase64 call, it should be like this: accountKey + ":" + accountKey

Sandrino Di Mattia
- 24,739
- 2
- 60
- 65
-
The way seems to be correct but something in the setRequestProperty must be differenet because this way I get the responce message "Basic authentication is required. Enter account key as password. – Themis Mavridis Jun 21 '12 at 15:27
-
Your new code produces a "Bad Request". I have also tried httpsCon.setRequestProperty("Authorization: Basic",accountKeyEnc); but I got again the message "Basic authentication is required..." @sandrinodimattia – Themis Mavridis Jun 21 '12 at 16:16
-
Does this code help? https://github.com/carrot2/carrot2/tree/master/core/carrot2-source-microsoft/src/org/carrot2/source/microsoft – Themis Mavridis Jun 21 '12 at 16:23
-
If you get a Bad Request I'm assuming the authentication is OK but there's something wrong with the actual request. What is the complete url you are using (did you handle the url encode for example)? What data are you sending? – Sandrino Di Mattia Jun 21 '12 at 19:34
-
The url I open connection for is "https://api.datamarket.azure.com/Bing/Search/Web?&Query=%27bbc%27&$top=10". The connection I open is an HttpsURLConnection with name httpsCon. After the line httpsCon.setRequestProperty(....) I just try to see if its connected well through the method getResponseCode which produces code 400 and through getResponceMessage that produces a string "Bad Request". – Themis Mavridis Jun 21 '12 at 20:07
-
I found the problem of my bad request! I have put $ in front of Query...thanks man for the help! – Themis Mavridis Jun 21 '12 at 20:30