Saya membuat permintaan posting OCR ke MS ccomputer visions API dan mengembalikan respons: HTTP/1.1 415 Jenis Media yang Tidak Didukung [Kontrol Cache: no-cache, Pragma: no-cache, Content-Length: 183, Content- Jenis: aplikasi/json; dll.

Inilah kode Java saya, menambahkan multipartfile(jpg) ke permintaan dan kemudian mempostingnya.

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;
}

Ada bantuan? Bersulang!

0
user6067304 27 November 2017, 16:43

1 menjawab

Jawaban Terbaik

Akan jauh lebih sederhana jika Anda hanya memposting satu muatan gambar ke dalam badan POST, daripada membuat badan MIME multi-bagian, karena Anda hanya dapat memposting satu gambar pada satu waktu. Kode bisa terlihat seperti ini:

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));
}

Perhatikan bahwa API mengharapkan application/octet-stream sebagai tipe konten, bukan image/*.

0
cthrash 28 November 2017, 02:43