在Java中使用Unirest进行多部分文件上传请求

时间:2018-08-31 10:19:05

标签: java post file-upload multipart unirest

我能够使用REST客户端(失眠)发布此请求。但是,当我无法编写适当的代码以在Java中执行相同的操作时。以下是我的失眠要求的样子。

enter image description here

下面是客户端生成的代码的样子。

HttpResponse<String> response = Unirest.post("http://172.16.6.15:5053/image-service/services/image-panel-service/panel/images?=")
  .header("com.yatra.tenant.header.tenantid", "1051")
  .header("content-type", "multipart/form-data; boundary=---011000010111000001101001")
  .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"imageFile\"\r\n\r\n")
  .asString();

下面是我用Java写的无效代码。

try {
            HttpResponse<String> response = Unirest.post("http://172.16.6.15:5053/image-service/services/image-panel-service/panel/images")
            .header("com.yatra.tenant.header.tenantid", "1051")
            .header("content-type", "multipart/form-data")
            .field("imageFile", new File("Desert.jpg"))
            .field("imageData", new File("ImageUploadRequest.json")).asString();

            System.out.println(response.getBody());

        } catch (UnirestException e) {
            e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:3)

try {
    MultipartBody body = Unirest.post("http://localhost:4849/upload/images")
        .field("name", "bingoo.txt")
        .field("files", temp1)
        .field("files", temp2)
        .field("files", temp3);
    HttpResponse<String> file = body.asString();
    System.out.println(file.getStatus());

} catch (Exception e) {
    e.printStackTrace();
}
来自https://www.programcreek.com/java-api-examples/?api=com.mashape.unirest.request.body.MultipartBody

摘要

答案 1 :(得分:0)

他们文档中的摘录 http://kong.github.io/unirest-java/#file-uploads

 Unirest.post("http://httpbin.org")
   .field("imageFile", new File("JellyFirst.jpg"))
   .asEmpty();