使用HttpClient调用接口并传递参数

//HttpClient用于调用接口
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("http://www.xxxx.com/lticketsSys/handlerfloder/zwfwPro.ashx?opekey=ZXKJ");
//		HttpPost httpPost = new HttpPost("http://xxxxxx/lticketsSys/handlerfloder/zwfwPro.ashx?opekey=ZXKJ");
		
		
		//list为传递给接口的所有参数
		List<NameValuePair> list = new ArrayList<NameValuePair>();			//该list为传递给httpClient的参数
		
		BasicNameValuePair basicNameValuePair1 = new BasicNameValuePair("baseInfoXml",baseInfoXmlStr.toString());
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("attrXml", attrXmlStr.toString());
		BasicNameValuePair basicNameValuePair3 = new BasicNameValuePair("formXml", formXmlStr.toString());
		
		
		list.add(basicNameValuePair1);
		list.add(basicNameValuePair2);
		list.add(basicNameValuePair3);
		

		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+JSON.toJSONString(list));
		UrlEncodedFormEntity formEntity;
		CloseableHttpResponse response=null;
		String responseStr=null;
		try {
			//把参数list转为Entity类型提交,并设置字符格式为UTF-8
			formEntity = new UrlEncodedFormEntity(list,HTTP.UTF_8);
			
			//把Entity设置到post里面
			httpPost.setEntity(formEntity);
			//访问接口
			response = httpClient.execute(httpPost);
			//接口的返回参数
			HttpEntity entity = response.getEntity();
			responseStr = EntityUtils.toString(entity,"UTF-8");
			
			System.out.println("接口返回的数据===========******************************"+responseStr);
			
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				if(response != null){
					response.close();
				}
				if(httpClient != null){
					httpClient.close();
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

以下为httpGet传递参数的方式,除了传参,其他相同

List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("jsonStr", JSON.toJSONString(myMap)));



String params = EntityUtils.toString(new UrlEncodedFormEntity(list,HTTP.UTF_8));


HttpGet httpGet = new HttpGet("http://10.54.19.73/xxx/xx/xxPdfByCode"+"?"+params);

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值