使用httpclient传输流加普通字段

import java.io.File;
import java.nio.charset.Charset;


import org.apache.http.HttpEntity;
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;
import org.junit.Test;


public class MyTest {
	@Test
	public void test2() {
		try {
			HttpClient httpClient = HttpClientBuilder.create().build();
			HttpPost httpPost = new HttpPost("");// 请求地址
			MultipartEntityBuilder meb = MultipartEntityBuilder.create();
			ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
			meb.addBinaryBody("file1", new File(""));// 需要传输的文件,参数也可以是流
			meb.addTextBody("username", "陈智勇", strContent);// 普通字段,指定编码
			HttpEntity httpEntity = meb.build();
			httpPost.setEntity(httpEntity);
			httpClient.execute(httpPost);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}

可以使用HttpClient的HttpPost方法来传输json格式的参数,具体步骤如下: 1. 创建HttpClient对象: ``` CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpPost对象: ``` HttpPost httpPost = new HttpPost(url); ``` 其中,url是接收请求的API地址。 3. 设置请求头: ``` httpPost.setHeader("Content-Type", "application/json"); ``` 4. 创建请求参数: ``` JSONObject json = new JSONObject(); json.put("param1", "value1"); json.put("param2", "value2"); StringEntity entity = new StringEntity(json.toString(), "UTF-8"); ``` 其中,param1和param2是接口需要的参数名,value1和value2是参数的具体值。StringEntity将json对象转换为字符串形式,并设置字符编码为UTF-8。 5. 设置请求参数: ``` httpPost.setEntity(entity); ``` 6. 发送请求并获取响应: ``` CloseableHttpResponse response = httpClient.execute(httpPost); ``` 7. 处理响应结果: ``` HttpEntity responseEntity = response.getEntity(); String result = EntityUtils.toString(responseEntity, "UTF-8"); ``` 其中,result即为接口返回的结果,可以根据实际需求进行处理。 完整代码示例: ``` CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json"); JSONObject json = new JSONObject(); json.put("param1", "value1"); json.put("param2", "value2"); StringEntity entity = new StringEntity(json.toString(), "UTF-8"); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String result = EntityUtils.toString(responseEntity, "UTF-8"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值