java后台模拟multipart/form-data请求 上传文件和普通文本的两种方法

本地文件

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.core.io.FileSystemResource;
import java.io.File;

	RestTemplate restTemplate = new RestTemplate();
	String apiUrl = "http://192.91.4.213:9092/data_dump/v1/lead";
    HttpHeaders headers = new HttpHeaders();
    MultiValueMap<String, Object> map= new LinkedMultiValueMap<>()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Java中的multipart/form-data请求,用于上传和下载文件,你可以使用Java的HttpURLConnection或Apache HttpClient库来完成。 首先,我们来看一下如何使用HttpURLConnection来发送multipart/form-data请求进行文件上传: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class MultipartUploader { public static void main(String[] args) throws IOException { // 请求URL URL url = new URL("http://example.com/upload"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); // 设置请求头 conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); // 构建请求体 try (OutputStream outputStream = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true)) { // 添加文件参数 File file = new File("/path/to/file.txt"); writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n") .append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + "\r\n\r\n") .flush(); FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); fileInputStream.close(); // 添加其他参数 writer.append("\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"name\"\r\n\r\n") .append("John Doe\r\n") .flush(); // 请求结束标志 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--").flush(); } // 获取响应 int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 响应处理 } else { // 错误处理 } conn.disconnect(); } } ``` 上述代码中,我们使用`HttpURLConnection`创建了一个POST请求,并设置了请求头的`Content-Type`为`multipart/form-data`,同时构建了请求体包含文件和其他参数。发送请求后,可以通过`conn.getResponseCode()`获取响应码,进而对响应进行处理。 接下来,我将展示如何使用Apache HttpClient来发送multipart/form-data请求进行文件上传和下载: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; 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.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.File; import java.io.IOException; public class MultipartUploader { public static void main(String[] args) throws IOException { // 创建HttpClient try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // 创建HttpPost请求 HttpPost httpPost = new HttpPost("http://example.com/upload"); // 构建请求MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文件参数 File file = new File("/path/to/file.txt"); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); builder.addPart("file", fileBody); // 添加其他参数 builder.addTextBody("name", "John Doe"); // 设置请求体 HttpEntity multipartEntity = builder.build(); httpPost.setEntity(multipartEntity); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpPost); // 处理响应 int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // 响应处理 } else { // 错误处理 } } } } ``` 上述代码中,我们使用了Apache HttpClient库来创建了一个HttpPost请求,然后通过`MultipartEntityBuilder`构建了请求体,添加了文件和其他参数。发送请求后,可以通过`response.getStatusLine().getStatusCode()`获取响应码,进而对响应进行处理。 至于文件下载的请求,你可以使用`HttpGet`请求来实现。具体代码类似于上述的文件上传示例,只需要将HttpPost替换为HttpGet,并设置请求URL即可。 希望这些示例代码能帮助到你进行multipart/form-data请求的文件上传和下载。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值