android 为什么我无法为Bing API取回任何内容

izj3ouym  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(119)

我只是不能得到任何东西从Bing img搜索API,这里是这个API的细节.
https://dev.cognitive.microsoft.com/docs/services/56b43f0ccf5ff8098cef3808/operations/56b4433fcf5ff8098cef380c
由于HttpClient已被弃用,所以我使用httpURLconnection,有人能告诉我我的代码有什么问题吗?
所有的参数和关键是好的,我在网站上测试.

  1. public void run() {
  2. HttpURLConnection connection = null;
  3. try {
  4. URL url = new URL("https://api.cognitive.microsoft.com/bing/v5.0/images/search");
  5. connection = (HttpURLConnection) url.openConnection();
  6. connection.setRequestMethod("POST");
  7. connection.setDoInput(true);
  8. connection.setDoOutput(true);
  9. connection.setConnectTimeout(8000);
  10. connection.setReadTimeout(8000);
  11. connection.setUseCaches(false);
  12. connection.setRequestProperty("Ocp-Apim-Subscription-Key", "562eaaada4b644f2bea31a454f26d905");
  13. OutputStream out = connection.getOutputStream();
  14. DataOutputStream params =new DataOutputStream(out);
  15. params.writeBytes("q=dog&count=10&offset=0&mkt=en-us&safeSearch=Moderate");
  16. out.close();
  17. connection.connect();
  18. InputStream in = connection.getInputStream();
  19. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  20. StringBuilder response = new StringBuilder();
  21. String line;
  22. while ((line = reader.readLine()) != null) {
  23. response.append(line);
  24. }
  25. Message message = new Message();
  26. message.what = SHOW_RESPONSE;
  27. message.obj = response.toString();
  28. handler.sendMessage(message);
  29. } catch (Exception e) {
  30. // TODO: handle exception
  31. } finally {
  32. if (connection != null) {
  33. connection.disconnect();
  34. }
  35. }
  36. }

字符串

koaltpgm

koaltpgm1#

假设您正在执行“POST”调用ImageInsights。
ImageInsights

  1. connection .setRequestProperty("Content-Type", "multipart/form-data");

字符串
这里的内容是错误的

  1. params.writeBytes("q=dog&count=10&offset=0&mkt=en-us&safeSearch=Moderate");//
  2. it takes post post body not query param String.


对于搜索API,是“GET”调用而不是“POST”调用
搜索API

  1. https://api.cognitive.microsoft.com/bing/v5.0/images/search[?q][&count][&offset][&mkt][&safeSearch]
  2. here every this is in url query string, you have write it in outputstream


检查下面的示例(你可以尝试那里的API示例)

  1. URL url = new URL("https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats&count=10&offset=0&mkt=en-us&safeSearch=Moderate");
  2. connection = (HttpURLConnection) url.openConnection();
  3. connection.setRequestMethod("GET");
  4. connection.setDoInput(true);
  5. connection.setDoOutput(true);
  6. connection.setConnectTimeout(8000);
  7. connection.setReadTimeout(8000);
  8. connection.setUseCaches(false);

展开查看全部

相关问题