2016-11-22 31 views
1
final String accountKey = "***********************"; 
    final String bingUrlPattern ="https://api.cognitive.microsoft.com/bing/v5.0/search?q=bill gates"; 


    String query = URLEncoder.encode("'what  is omonoia'", Charset.defaultCharset().name()); 
    String bingUrl = String.format(bingUrlPattern, query); 

    String accountKeyEnc = Base64.getEncoder().encodeToString((accountKey + ":" + accountKey).getBytes()); 

    URL url = new URL(bingUrl); 
    URLConnection connection = url.openConnection(); 
    connection.setRequestProperty("Authorization", "Basic " + accountKeyEnc); 

    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { 
     String inputLine; 
     StringBuilder response = new StringBuilder(); 
     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
     JSONObject json = new JSONObject(response.toString()); 
     JSONObject d = json.getJSONObject("d"); 
     JSONArray results = d.getJSONArray("results"); 
     int resultsLength = results.length(); 
     for (int i = 0; i < resultsLength; i++) { 
      final JSONObject aResult = results.getJSONObject(i); 
      System.out.println(aResult.get("Url")); 
     } 
    } 
} 

代码在执行时返回400错误代码。 看来url模式的格式是错误的。请建议。 也可以如何指定格式为JSON。我正在尝试为网络结果使用微软认知搜索api

回答

0

您正在错误地指定您的身份验证。你会想,而不是执行以下操作:

connection.setRequestProperty("Ocp-Apim-Subscription-Key", accountKey); 

你也想改变URL是如何构建的,因为你已经硬编码查询到“比尔·盖茨”。

final String bingUrlPattern ="https://api.cognitive.microsoft.com/bing/v5.0/search?q=%s"; 

您可能会感兴趣API console对您有所帮助。

相关问题