I am successfully downloading images from the Bing's-Search-API in Java. However, I don't understand how to handle responses.

For instance, if images are not found, or if the user tries to search for adult content (even if it is set to moderate), how should I catch theses responses?

Thank you very much.

Here is my code:

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  
    } 
有帮助吗?

解决方案

You can use Gson:

    Gson gson = (new GsonBuilder()).create();
BingSearchResults bingSearchResults = gson.fromJson(res, BingSearchResults.class);

with the following 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;
}

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top