计算机视觉 OCR API 返回 http 响应:Java http 请求不支持媒体类型

Computer Vision ocr API returning http response: Unsupported Media Type for Java http request

我正在向 MS ccomputer visions APi 发出 OCR post 请求,它 returns 响应:HTTP/1.1 415 Unsupported Media Type [Cache -Control: no-cache, Pragma: no-cache, Content-Length: 183, Content-Type: application/json;等等等等

这是我的 Java 代码,将一个多部分文件 (jpg) 添加到请求中,然后 posting 它。

HttpClient httpClient = HttpClientBuilder.create().build();

    String fileContentType = file.getContentType();
    URI uri = buildUri();

    if(uri == null){
        //throw some exception
    }

    HttpPost request = new HttpPost(uri);

    request.setHeader("Content-Type", fileContentType);
    request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);

    MultipartEntityBuilder mpEB = MultipartEntityBuilder.create();


    InputStream fileInputStream = file.getInputStream();

    //modify method to add filename if later need arises
    //link: https://memorynotfound.com/apache-httpclient-multipart-upload-request/
    mpEB.addBinaryBody("image", fileInputStream);
    mpEB.setContentType(ContentType.MULTIPART_FORM_DATA);

    HttpEntity image = mpEB.build();
    request.setEntity(image);

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

    System.out.println(json.toString());
    //dataFromJsonExtractor.extractData(json);

}
private URI buildUri(){

    URI link = null;
    try {
        URIBuilder builder = new URIBuilder(uriBase);

        builder.setParameter("language", "de");

        URI uri = builder.build();

        link = uri;
        }catch (URISyntaxException e){
        logger.debug("Computer Vision API URL Builder creation error: " + e);

    }

    return link;
}

有什么帮助吗?干杯!

如果您只是 post 将单个图像有效负载放入 POST 正文,而不是构建多部分 MIME 正文,那将会简单得多,因为您只能 post 无论如何,一次一张图片。代码可能如下所示:

public static void run(FileDataSource file) throws Exception
{
    HttpClient httpClient = HttpClientBuilder.create().build();

    URI uri = buildUri();

    HttpPost request = new HttpPost(uri);

    request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);

    HttpEntity entity = EntityBuilder
        .create()
        .setStream(file.getInputStream())
        .setContentType(ContentType.APPLICATION_OCTET_STREAM)
        .build();

    request.setEntity(entity);

    HttpResponse response = httpClient.execute(request);
    HttpEntity jsonEntity = response.getEntity();

    System.out.println(EntityUtils.toString(jsonEntity));
}

请注意,API 期望 application/octet-stream 作为内容类型,而不是 image/*