Java 9 HttpClient send a multipart/form-data request

前端 未结 6 1223
孤街浪徒
孤街浪徒 2020-12-09 05:05

Below is a form:

6条回答
  •  执念已碎
    2020-12-09 05:21

    A direction in which you can attain making a multiform-data call could be as follows:

    BodyProcessor can be used with their default implementations or else a custom implementation can also be used. Few of the ways to use them are :

    1. Read the processor via a string as :

      HttpRequest.BodyProcessor dataProcessor = HttpRequest.BodyProcessor.fromString("{\"username\":\"foo\"}")
      
    2. Creating a processor from a file using its path

      Path path = Paths.get("/path/to/your/file"); // in your case path to 'img'
      HttpRequest.BodyProcessor fileProcessor = HttpRequest.BodyProcessor.fromFile(path);
      

    OR

    1. You can convert the file input to a byte array using the apache.commons.lang(or a custom method you can come up with) to add a small util like :

      org.apache.commons.fileupload.FileItem file;
      
      org.apache.http.HttpEntity multipartEntity = org.apache.http.entity.mime.MultipartEntityBuilder.create()
             .addPart("username",new StringBody("foo", Charset.forName("utf-8")))
             .addPart("img", newFileBody(file))
             .build();
      multipartEntity.writeTo(byteArrayOutputStream);
      byte[] bytes = byteArrayOutputStream.toByteArray();
      

      and then the byte[] can be used with BodyProcessor as:

      HttpRequest.BodyProcessor byteProcessor = HttpRequest.BodyProcessor.fromByteArray();
      

    Further, you can create the request as :

    HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("http:///example/html5/demo_form.asp"))
                .headers("Content-Type","multipart/form-data","boundary","boundaryValue") // appropriate boundary values
                .POST(dataProcessor)
                .POST(fileProcessor)
                .POST(byteProcessor) //self-sufficient
                .build();
    

    The response for the same can be handled as a file and with a new HttpClient using

    HttpResponse.BodyHandler bodyHandler = HttpResponse.BodyHandler.asFile(Paths.get("/path"));
    
    HttpClient client = HttpClient.newBuilder().build();
    

    as:

    HttpResponse response = client.send(request, bodyHandler);
    System.out.println(response.body());
    

提交回复
热议问题