java中CloseableHttpClient实现附带formdata参数userId实现上传文件

2023-12-28 15:44:23

在Java中使用CloseableHttpClient来实现附带form data参数userId实现上传文件,可以使用HttpPost请求,然后通过MultipartEntityBuilder来构建请求体:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

public class FileUploader {
    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://example.com/upload");

        // 构建请求体,添加文件和form data参数
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("file", new File("path/to/file")); // 添加文件
        builder.addTextBody("userId", "123"); // 添加form data参数
        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);

        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);
            
            // 处理响应结果
            System.out.println(responseBody);
            
            // 关闭连接
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请记得将上述代码中的http://example.com/upload替换为实际的上传文件地址,并将path/to/file替换为实际文件的路径。

文章来源:https://blog.csdn.net/m0_37649480/article/details/135260892
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。