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

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 "";
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用`RestTemplate`的`postForEntity`方法来发送HTTP POST请求,同时携带文件流和其他参数。具体可以参考下面的示例代码: ```java import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class RestClient { public static void main(String[] args) throws IOException { String url = "http://example.com/upload"; // 设置请求HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 设置请求体 MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); // 添加文件流 Path filePath = Paths.get("path/to/file.txt"); byte[] fileBytes = Files.readAllBytes(filePath); Resource fileResource = new ByteArrayResource(fileBytes) { @Override public String getFilename() { return filePath.getFileName().toString(); } }; body.add("file", fileResource); // 添加其他参数 body.add("param1", "value1"); body.add("param2", "value2"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class); System.out.println(response.getBody()); } } ``` 在上面的示例代码中,我们首先设置了请求头,指定了请求体的类型为`multipart/form-data`。然后构造了一个`MultiValueMap`对象,用于存储请求体的键值对。通过`ByteArrayResource`类可以将文件流转化为Spring的`Resource`对象,并将其添加到请求体中。最后,我们使用`postForEntity`方法发送HTTP POST请求,并将响应的内容解析为字符串。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小安灬

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

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

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

打赏作者

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

抵扣说明:

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

余额充值