我已成功从Bing's-Search-API
中的Java
下载图片。但是,我不明白如何处理回复。
例如,如果找不到图片,或者用户试图搜索成人内容(即使设置为中等),我应该如何catch
这些回复?
非常感谢。
这是我的代码:
public void SearchWithBing(String search){
search = search.replaceAll(" ", "%20");
String accountKey="acKey";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/Image?Query=%27" + search + "%27&$top=50&$format=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
gsonParser(output);
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//EndOfBingSearch
}
答案 0 :(得分:1)
你可以使用Gson:
Gson gson = (new GsonBuilder()).create();
BingSearchResults bingSearchResults = gson.fromJson(res, BingSearchResults.class);
使用以下课程:
public class BingSearchResults {
public ResultsContent d;
public static class ResultsContent {
public Result[] results;
public String __next;
}
public static class Result {
public String ID;
public String Title;
public String Description;
public String DisplayUrl;
public String Url;
public Metadata __metadata;
}
public static class Metadata {
public String uri;
public String type;
}
}