HttpClients发送带文件的post请求

本文介绍了一种使用HttpClients发送带文件的POST请求的方法,并解决了因RequestBody注解导致的接收不到请求的问题。通过示例代码展示了如何正确设置MultipartEntityBuilder以发送文件。

使用HttpClients发送带文件的post请求网上代码不少,我主要是遇到了一个无法接收到请求的问题。后来试了很多方法发现是RequestBody这个注解的问题,去掉这个注解就好了。这么简单的问题,有时候就是容易忽略,特意记一下吧。
顺便贴一下我的发送请求的代码吧。

File file = new File(fullPath);
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(FilePushSet.PUSHURL.getMsg());
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
     MultipartEntityBuilder builder = MultipartEntityBuilder.create();
     builder.setCharset(StandardCharsets.UTF_8);
     builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
     String fileName = multipartFile.getOriginalFilename();
            // 文件流
     builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            //表单中其他参数,如果没有其他参数可以注释该部分
      builder.addPart("md5",new StringBody(FilePushSet.MD5.getMsg(), ContentType.create("text/plain", Consts.UTF_8)));

      HttpEntity entity = builder.build();
      httpPost.setEntity(entity);
     // 执行提交
     HttpResponse response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      // 返回
       String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

因为一开始想的是需要转换成MultipartFile,其实不转换,在builder.addBinaryBody这里直接使用文件输入流也是可以的,但是懒得再去改了。

要使用HttpClient发送文件和参数的POST请求,您可以按照以下步骤进行操作: 1. 导入所需的类: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.HttpClients; ``` 2. 创建HttpClient实例: ```java HttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建HttpPost请求对象: ```java HttpPost httpPost = new HttpPost(url); ``` 其中,`url`是目标URL。 4. 创建MultipartEntityBuilder对象,并添加文件和参数: ```java MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", new FileBody(file)); // 添加文件 builder.addPart("param1", new StringBody(param1, ContentType.TEXT_PLAIN)); // 添加参数1 builder.addPart("param2", new StringBody(param2, ContentType.TEXT_PLAIN)); // 添加参数2 ``` 其中,`file`是要上传的文件,`param1`和`param2`是需要传递的参数。 5. 构建HttpEntity并设置给HttpPost请求对象: ```java HttpEntity multipartEntity = builder.build(); httpPost.setEntity(multipartEntity); ``` 6. 执行HttpPost请求并获取响应: ```java HttpResponse response = httpClient.execute(httpPost); ``` 7. 处理响应结果: ```java int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); // 处理响应实体 ``` 完整的示例代码如下: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.HttpClients; import java.io.File; import java.io.IOException; public class HttpClientExample { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file"; String param1 = "value1"; String param2 = "value2"; HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", new FileBody(new File(filePath))); builder.addPart("param1", new StringBody(param1, ContentType.TEXT_PLAIN)); builder.addPart("param2", new StringBody(param2, ContentType.TEXT_PLAIN)); HttpEntity multipartEntity = builder.build(); httpPost.setEntity(multipartEntity); try { HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); // 处理响应实体 } catch (IOException e) { e.printStackTrace(); } } } ``` 请注意,上述示例中使用的是Apache HttpClient 4.x版本。在使用之前,请确保已经添加相关的依赖。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值