尝试使用 bing azure marketpalce 的搜索 api 与 java 我有这个代码:
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 class BingAPI2 {
public static void main(String[] args) throws Exception{
BingAPI2 b = null;
b.getBing();
}
public static void getBing() throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
String accountKey = "myAccountKey=";
byte[] accountKeyBytes = Base64.encodeBase64((":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
HttpGet httpget = new HttpGet("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?$Query=%27Datamarket%27&$format=json");
httpget.setHeader("Authorization", "Basic <"+accountKeyEnc+">");
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();
}
}
}
我收到错误:
Exception in thread "main" org.apache.http.client.HttpResponseException: The authorization type you provided is not supported. Only Basic and OAuth are supported
最佳答案
我首先看到的是你的台词
byte[] accountKeyBytes = Base64.encodeBase64((":"+ accountKey).getBytes());
应该阅读:
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":"+ accountKey).getBytes());
您使用 apache 库也是有原因的吗?我用于从 bing 获取 json 对象的代码使用 java.net,如下所示:
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStreamReader;
class BingJson{
JSONObject getJSONfromBing(String term){
try{
URLConnection c = new URL(term).openConnection();
String key = (DatatypeConverter.printBase64Binary(("XXX" + ":" + "XXX").getBytes("UTF-8")));
c.setRequestProperty("Authorization", String.format("Basic %s",key));
c.connect();
//etc.
}
}
要构建 json 对象,我会说遵循以下代码: Convert InputStream to JSONObject
关于java - 使用 java 搜索 bing azure 市场的 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769123/