Java 9 HttpClient发送multipart / form-data请求 [英] Java 9 HttpClient send a multipart/form-data request

查看:1815
本文介绍了Java 9 HttpClient发送multipart / form-data请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是表格:

<form action="/example/html5/demo_form.asp" method="post" 
enctype="multipart/form-data">
   <input type="file" name="img" />
   <input type="text" name=username" value="foo"/>
   <input type="submit" />
</form>

当提交此表格时,请求将如下所示:

when will submit this form, the request will look like this:

POST /example/html5/demo_form.asp HTTP/1.1
Host: 10.143.47.59:9093
Connection: keep-alive
Content-Length: 326
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://10.143.47.59:9093
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryEDKBhMZFowP9Leno
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4

Request Payload
------WebKitFormBoundaryEDKBhMZFowP9Leno
Content-Disposition: form-data; name="username"

foo
------WebKitFormBoundaryEDKBhMZFowP9Leno
Content-Disposition: form-data; name="img"; filename="out.txt"
Content-Type: text/plain


------WebKitFormBoundaryEDKBhMZFowP9Leno--

请注意请求有效负载,你可以看到表格中的两个参数,用户名和img(表单数据;名称= img; filename =out.txt),并且finename是文件系统中的真实文件名(或路径),您将在后端通过名称(而不是文件名)接收文件(例如spring controller)。

如果我们使用Apache Httpclient来模拟请求,我们将编写这样的代码:

please pay attention to the "Request Payload", you can see the two params in the form, the username and the img(form-data; name="img"; filename="out.txt"), and the finename is the real file name(or path) in your filesystem, you will receive the file by name(not filename) in your backend(such as spring controller).
if we use Apache Httpclient to simulate the request, we will write such code:

MultipartEntity mutiEntity = newMultipartEntity();
File file = new File("/path/to/your/file");
mutiEntity.addPart("username",new StringBody("foo", Charset.forName("utf-8")));
mutiEntity.addPart("img", newFileBody(file)); //img is name, file is path

但在java 9中,我们可以编写这样的代码: / p>

But in java 9, We could write such code:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.
        newBuilder(new URI("http:///example/html5/demo_form.asp"))
       .method("post",HttpRequest.BodyProcessor.fromString("foo"))
       .method("post", HttpRequest.BodyProcessor.fromFile(Paths.get("/path/to/your/file")))
       .build();
HttpResponse response = client.send(request, HttpResponse.BodyHandler.asString());
System.out.println(response.body());

现在你看,我怎样才能设置参数的名称?

Now you see, how could I set the "name" of the param?

推荐答案

您可以通过以下方式进行 multiform-data 调用:

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

BodyProcessor 可以与其默认实现一起使用,也可以使用自定义实现。几乎没有使用它们的方法是:

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. 通过字符串读取处理器:

  1. Read the processor via a string as :

HttpRequest.BodyProcessor dataProcessor = HttpRequest.BodyProcessor.fromString("{\"username\":\"foo\"}")


  • 使用路径从文件创建处理器

  • 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. 您可以使用 apache.commons.lang (或你可以提出的自定义方法)添加一个小的工具,如:

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

    然后byte []可以与 BodyProcessor as:

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






    同样的响应可以作为文件并使用新的 HttpClient 使用

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

    这篇关于Java 9 HttpClient发送multipart / form-data请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆