Java基础-http post带有文件、参数的请求

本文介绍如何使用Java的Apache HttpClient库进行HTTP Post请求,包括文件上传和参数传递。示例代码展示了如何构建MultipartEntity,设置请求头,以及处理响应。

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

pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.6</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.1</version>
</dependency>

发送端:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.impl.client.HttpClientBuilder;

/**
 * <dependency> 
	 * <groupId>org.apache.httpcomponents</groupId> 
	 * <artifactId>httpclient</artifactId> 
	 * <version>4.3.6</version> 
 * </dependency> 
 * <dependency> 
	 * <groupId>org.apache.httpcomponents</groupId> 
	 * <artifactId>httpmime</artifactId> 
	 * <version>4.5</version> 
 * </dependency> 
 * <dependency> 
	 * <groupId>org.apache.httpcomponents</groupId> 
	 * <artifactId>httpcore</artifactId> 
	 * <version>4.4.1</version> 
 * </dependency>
 */
public class PostTest {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost("http://10.48.47.131:9091/toolCenter/attach");// 请求地址
		MultipartEntityBuilder meb = MultipartEntityBuilder.create();
		ContentType strContent = ContentType.create("application/zip", Charset.forName("UTF-8"));
		meb.addBinaryBody("uploadfile", new File("D://文件.zip"));// 文件路径
		meb.addTextBody("fileName", "文件.zip", strContent);// 文件名
		meb.addTextBody("sendMailName", "主标题", strContent);
		meb.addTextBody("mailSubject", "子标题", strContent);
		meb.addTextBody("receiveMail", "anyf@kunyitech.com", strContent);//多个以;分割
		meb.addTextBody("mailContent", "邮件内容", strContent);
		HttpEntity httpEntity = meb.build();
		httpPost.setEntity(httpEntity);
		try {
			StringBuilder sb = new StringBuilder();
			String line;
			HttpResponse httpResponse = httpClient.execute(httpPost);
			InputStream inputStream = httpResponse.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			String rspMsg = URLDecoder.decode(sb.toString(),"UTF-8");
			System.err.println(rspMsg); // {"resp_desc":"SUCCESS","resp_code":"0000"}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

接收端:

@RequestMapping(value = "/emailattach", produces = "application/json; charset=utf-8")
@ResponseBody
public String email(
	@RequestParam("uploadfile")MultipartFile uploadfile,
	@RequestParam("param1")String param1,
	@RequestParam("param2")String param2
) {
	log.info("receive_param1-{},param2:{}",param1,param2);
	try {
		String filePath = "/app/" + filename;
		File file = new File(filePath);
		uploadfile.transferTo(file );
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
	return "";
}
<think>好的,用户想了解如何用Java发送带文件上传的HTTP POST请求。首先,我需要回忆一下相关的知识,并结合提供的引用内容来构建回答。 根据引用[2],Java通过HttpURLConnection类处理POST请求上传文件,需要设置正确的Content-Type为multipart/form-data,并使用边界字符串分隔不同部分。引用[3]中提到需要根据文件后缀判断内容类型,比如image/jpeg等。引用[4]的示例代码可能也有关联,但具体内容未显示,可能需要依赖其他引用。 首先,我应该整理步骤:创建连接、设置请求方法、设置请求头、构建multipart/form-data格式的数据体,处理文件和其他字段,然后发送请求并处理响应。需要特别注意边界字符串的使用和格式正确性,否则服务器可能无法正确解析。 接下来,考虑代码示例。需要展示如何将文件和其他参数一起上传,比如使用FileInputStream读取文件,并正确写入输出流。同时,引用[3]中的getContentType方法可以帮助确定文件的MIME类型,需要在代码中体现。 可能遇到的问题包括流未正确关闭,边界格式错误,或者忘记设置Content-Length。此外,异常处理也是关键,比如捕获IOException并妥善处理。 最后,用户可能需要优化建议,比如使用Apache HttpClient或OkHttp库简化操作,这在引用[2]和[3]中提到的其他方法可以补充。不过用户明确要求Java原生实现,所以主要展示HttpURLConnection的用法。 总结回答结构:分步骤说明,代码示例,优化建议,相关问题。确保引用正确的来源,比如文件内容类型处理引用[3],POST请求基本结构引用[1]和[2]。</think>### Java发送带文件HTTP POST请求步骤 1. **创建HTTP连接对象**:使用`java.net.URL`和`HttpURLConnection`建立连接,并设置请求方法为`POST`。 2. **设置请求头**:指定`Content-Type`为`multipart/form-data`,并定义边界字符串(Boundary),例如`----WebKitFormBoundary7MA4YWxkTrZu0gW`。 3. **构建请求体**: - 文件部分:写入文件二进制数据,需包含文件名和内容类型(如`image/jpeg`)。 - 普通参数:通过键值对形式添加其他字段。 4. **发送数据并处理响应**:通过输出流写入请求体,输入流读取服务器返回结果。 ### 示例代码 ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploadExample { private static final String BOUNDARY = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; public static void main(String[] args) throws IOException { File file = new File("test.jpg"); URL url = new URL("https://api.example.com/upload"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); try (OutputStream os = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8"), true)) { // 添加文件参数 writer.append("--" + BOUNDARY).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n"); writer.append("Content-Type: " + getContentType(file) + "\r\n\r\n"); writer.flush(); try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); } // 添加普通参数(例如"user"字段) writer.append("\r\n--" + BOUNDARY).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"user\"\r\n\r\n"); writer.append("Alice\r\n"); // 结束标记 writer.append("--" + BOUNDARY + "--\r\n"); } // 处理响应 try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } } // 根据文件后缀判断内容类型(引用自示例代码[^3]) private static String getContentType(File file) { String fileName = file.getName().toLowerCase(); if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { return "image/jpeg"; } else if (fileName.endsWith(".png")) { return "image/png"; } else if (fileName.endsWith(".gif")) { return "image/gif"; } return "application/octet-stream"; } } ``` ### 关键优化建议 - **使用成熟库简化代码**:例如Apache HttpClient或OkHttp,可避免手动处理复杂的`multipart/form-data`格式[^2]。 - **异常处理**:添加`try-catch`块捕获`IOException`,确保连接和流正确关闭。 - **性能优化**:使用缓冲流(如`BufferedOutputStream`)提升大文件上传效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小安灬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值