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

本文介绍了使用Java后台模拟multipart/form-data请求来上传文件和普通文本的两种方法,包括从本地文件读取和使用文件流的操作。

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

本地文件

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<>();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    String filePath = "D:\\\\download\\XZZC.dump";
    FileSystemResource resource = new FileSystemResource(new File(filePath)); 
    map.add("ip", url);
    map.add("port",port);
    map.add("user",username);
    map.add("password",password);
    map.add("dbname",databasename);
    map.add("datafile",resource);
 	String result = restTemplate.postForObject(apiUrl, map, String.class);

文件流

	String filePostUrl = "http://192.91.4.213:9092/data_dump/v1/lead";      
	HttpPost httppost = new HttpPost(filePostUrl);
	HttpClient client = new DefaultHttpClient();
	MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();	
	try {
		entityBuilder.addBinaryBody("datafile", file.getInputStream(),
					ContentType.DEFAULT_BINARY, file.getName());
		entityBuilder.addTextBody("ip", url,ContentType.TEXT_PLAIN.withCharset("UTF-8"));
		entityBuilder.addTextBody("port", port,ContentType.TEXT_PLAIN.withCharset("UTF-8"));
		entityBuilder.addTextBody("user", username,ContentType.TEXT_PLAIN.withCharset("UTF-8"));
		entityBuilder.addTextBody("password", password,ContentType.TEXT_PLAIN.withCharset("UTF-8"));
		entityBuilder.addTextBody("dbname", databasename,ContentType.TEXT_PLAIN.withCharset("UTF-8"));
		httppost.setEntity(entityBuilder.build());
		HttpResponse response = client.execute(httppost);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String result = EntityUtils.toString(response.getEntity(), "UTF-8");
			String resultCode =	DataUtils.getResultCode(result);
		}else {
	        return resultBeanBuilder.state(new ResultBeanState(0,"error","数据库还原失败")).data(deploymentInstance).build();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
MultipartEntityBuilder 类需要的maven依赖是
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3.6</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值