httppost请求传递参数为file的集合

博客提及在HTTP POST请求中,当参数为普通字符串参数时,有特定的传参方式。围绕HTTP POST请求传参展开,重点关注普通字符串参数的传递情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.zjxt.demo.test;

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.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: heiheihaxi
 * @Date: 2019/4/26 10:02
 */
public class TestUploader {
    public static void main(String[] args) throws IOException {
        String url="http://localhost:8085/Uploader/";
        List<File> files = new ArrayList<>();
        File f1=new File("C:\\Users\\zzh\\Desktop\\tmp\\临时.jpg");
        File f2=new File("C:\\Users\\zzh\\Desktop\\tmp\\aaa.jpg");
        files.add(f1);
        files.add(f2);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //设置参数
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        // 解决乱码问题
        meBuilder.setCharset(Charset.forName("UTF-8"));
        meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (File file : files) {
            FileBody fileBody = new FileBody(file , ContentType.create("multipart/form-data",Charset.forName("UTF-8")));
            meBuilder.addPart("files", fileBody);
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(httpPost);
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                String result = EntityUtils.toString(resEntity,"utf-8");
                System.out.println(result);
            }
        }

    }
}

如果参数为普通的字符串参数,可以用以下方式

package com.zjxt.demo.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: heiheihaxi
 * @Date: 2019/4/26 10:23
 */
public class Test {
    public static void main(String[] args) throws IOException {
        String url="http://localhost:8087/Uploader/";

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost

        File f1=new File("C:\\Users\\zzh\\Desktop\\tmp\\bbb.mp3");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("fileName", f1.getName()));
        nvps.add(new BasicNameValuePair("lastModified", Long.toString(f1.lastModified())));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                System.out.println("responseEntity:"+responseEntity);
            }
            else{
                System.out.println("请求返回:"+state+"("+url+")");
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

### 如何在 Spring Boot 中发起 HTTP 请求 #### 使用 RestTemplate 发起 HTTP 请求 尽管官方推荐使用 `WebClient`,但在某些场景下仍可继续利用 `RestTemplate` 进行同步调用。以下是基于 `RestTemplate` 的简单 GET 和 POST 请求实现方法。 对于简单的 GET 请求: ```java // 创建 RestTemplate 实例 RestTemplate restTemplate = new RestTemplate(); // 执行GET请求并接收返回的结果 String result = restTemplate.getForObject("http://example.com/api", String.class); System.out.println(result); // 输出获取到的数据 ``` 针对带有参数的 GET 请求,则可以通过 URL 参数传递数据给服务器端[^1]。 当涉及到提交表单或 JSON 数据时,POST 方法更为常用: ```java // 构建要发送的对象实体 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, Object> map = new HashMap<>(); map.put("key", "value"); HttpEntity<Map<String, Object>> request = new HttpEntity<>(map, headers); // 发送POST请求并将响应转换为目标对象类型 ResponseEntity<String> response = restTemplate.postForEntity( "http://example.com/api/post", request, String.class ); System.out.println(response.getBody()); // 处理接收到的信息 ``` #### 使用 WebClient 发起 HTTP 请求 随着 Spring 5 推出了新的反应式编程模型,`WebClient` 成为了更现代化的选择,尤其适合处理异步操作和流式传输的大文件下载等需求。这里展示了一个基础的例子来说明怎样创建客户端实例以及执行相应的网络通信任务。 初始化 `WebClient.Builder` 并配置默认设置: ```java WebClient webClient = WebClient.builder() .baseUrl("https://api.example.com") // 设置API的基础URL地址 .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .build(); // 构造最终版本供后续调用 ``` 接着就可以轻松地发出各种类型的 HTTP 调用了。比如读取资源列表: ```java Mono<List<Item>> items = webClient.get() // 指定为GET方式 .uri("/items") // 添加具体的路径部分 .retrieve() // 获取远程服务回应体中的内容 .bodyToFlux(Item.class) // 将JSON数组映射成Java集合形式 .collectList(); // 收集所有的Item记录形成完整的列表 ``` 而上传多部件(Multipart)表单则显得更加直观简洁: ```java MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("file", resource); // 加入待传送的二进制资料项 builder.part("description", "This is a test file."); // 同时附带其他字段信息 webClient.post().uri("/upload") .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(builder.build())) .exchange() .flatMap(clientResponse -> clientResponse.bodyToMono(String.class)) .subscribe(System.out::println); // 订阅事件监听器用于打印输出结果 ``` 上述两种方案均能有效地满足不同业务逻辑下的 API 调用需求,不过考虑到未来维护性和性能优化方面的原因,在新建项目里优先考虑采用 `WebClient` 是明智之举[^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值