Reputation: 11
I just can't get any thing back from Bing img search API, here is the details of this API.
Since HttpClient is deprecated so I use httpURLconnection
, can somebody tell me what is wrong with my code ?
All the params and the key are good, I have tested on the web site.
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("https://api.cognitive.microsoft.com/bing/v5.0/images/search");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setUseCaches(false);
connection.setRequestProperty("Ocp-Apim-Subscription-Key", "562eaaada4b644f2bea31a454f26d905");
OutputStream out = connection.getOutputStream();
DataOutputStream params =new DataOutputStream(out);
params.writeBytes("q=dog&count=10&offset=0&mkt=en-us&safeSearch=Moderate");
out.close();
connection.connect();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
// TODO: handle exception
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Upvotes: 1
Views: 41
Reputation: 3874
Assuming your doing "POST" call for ImageInsights.
ImageInsights
connection .setRequestProperty("Content-Type", "multipart/form-data");
and the here contents are wrong
params.writeBytes("q=dog&count=10&offset=0&mkt=en-us&safeSearch=Moderate");//
it takes post post body not query param String.
For Search api is "GET" call not "POST" call
Search Api
https://api.cognitive.microsoft.com/bing/v5.0/images/search[?q][&count][&offset][&mkt][&safeSearch]
here every this is in url query string, you have write it in outputstream
check below sample(you can try there api sample )
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");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setUseCaches(false);
Upvotes: 0