使用CloseableHttpClient发送请求,以及HttpPost参数传递方式


依赖包信息

<!--CloseableHttpClient\HttpPost依赖-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.3</version>
</dependency>

<!--MultipartEntityBuilder依赖-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.10</version>
</dependency>

<!--NameValuePair\BasicNameValuePair\StringEntity依赖-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpcore</artifactId>
	<version>4.4.5</version>
</dependency>

一、发送请求

 try {
		CloseableHttpClient client = HttpClients.createDefault();
	    HttpPost httpPost = new HttpPost("xxxxx");//请求地址
	    
		... //传入参数
		
		HttpResponse response = client.execute(httpPost);
		if (response != null) {
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				/**获取json格式字符串  **/
				String respBody = EntityUtils.toString(resEntity, "UTF-8");
			}else{
                   //返回参数获取异常
               }
	 	}else{
          //客户端连接异常
        }
  } catch (Exception e) {
            e.printStackTrace();
  }
  

二、参数传递

一、普通参数传参
1. BasicNameValuePair 方式

NameValuePair(简单名称值对节点类型)使用该list来存放参数。
BasicNameValuePair 实现 apache http的NameValuePair接口。


	List<NameValuePair> list = new ArrayList<>();
	list.add(new BasicNameValuePair("参数A", "xxx"));
	list.add(new BasicNameValuePair("参数B", "xxx"));
	list.add(new BasicNameValuePair("参数C", "xxx"));
	httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF_8"));
           
2. 字符串拼接方式
 	StringBuffer sbr = new StringBuffer();
	sbr.append("参数A=xxx&");
	sbr.append("参数B=xxx&");
	sbr.append("参数C=xxx");
	StringEntity stringEntity = new StringEntity(sbr.toString(), "UTF-8");
	stringEntity.setContentType("application/x-www-form-urlencoded");
	httpPost.setEntity(stringEntity);
二、带有文件参数传参
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);

File pdfFile = new File("D:\\A.txt");
FileInputStream fileInputStream = new FileInputStream(pdfFile);

ContentType contentType1 = ContentType.create("multipart/form-data", Consts.UTF_8);
builder.addBinaryBody("binFile", fileInputStream, ContentType.MULTIPART_FORM_DATA, "B.txt");
ContentType contentType = ContentType.APPLICATION_JSON;
LinkedList<FormBodyPart> partsList = new LinkedList<>();
builder.addPart("参数A", new StringBody("xxx",contentType));
builder.addPart("参数A", new StringBody("xxx",contentType));
builder.addPart("参数A", new StringBody("xxx",contentType));
HttpEntity entity = builder.build();
httpPost.setEntity(entity);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值