在Jave中使用Bing Image API来搜索图像

时间:2017-06-15 06:31:51

标签: bing-api

我在此link找到了此示例代码 我用我的密钥替换{subscription key}但结果总是:

{ "statusCode": 404, "message": "Resource not found" }

我对这一行感到困惑:

StringEntity reqEntity = new StringEntity("{body}");

我应该将"{body}"替换为什么? https://dev.cognitive.microsoft.com示例中的完整代码位于

之下
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample 
{
    public static void main(String[] args) 
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/images/search");

            builder.setParameter("q", "cats");

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Content-Type", "multipart/form-data");
            request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");


            // Request body
            StringEntity reqEntity = new StringEntity("{body}");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) 
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这里的问题似乎是错误的方法。对于图像/搜索端点,http方法应为 GET 而不是POST。 POST方法为图像API提供了不同的端点 - 以获得洞察力。

所有端点都在这里:https://dev.cognitive.microsoft.com/docs/services/8336afba49a84475ba401758c0dbf749/operations/56b4433fcf5ff8098cef380c