HttpClient远程调用接口Post请求是所传参数为普通参数和Map

在工作中遇到了用HttpClient来做远程调用,因为之前一直没有用过这个东西,所以对这个HttpClient不是很友好,所以在网上找了一下资料,就找了以下方式,这两种方式的所传参数分别为普通参数和Map,现在记录在这里,方便以后自己查阅
在使用HttpClient之前,第一步当然是要加入依赖,依赖如下:

HttpClient依赖


    org.apache.httpcomponents
    httpclient
    4.5.2

引入fastjson依赖


			com.alibaba
			fastjson
			1.2.47
		

依赖添加完毕!
第一种调用方式,即参数为普通参数,直接上代码:

public  String getTokenId(String url)throws IOException {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpGet = new HttpPost(url);
		// 响应模型
		CloseableHttpResponse response = null;

		// 由客户端执行(发送)Post请求
		response = httpClient.execute(httpGet);
		// 从响应模型中获取响应实体
		HttpEntity responseEntity = response.getEntity();
		String s = EntityUtils.toString(responseEntity);
		return s;
	}

上面的url为访问地址加上所传的参数

第二种方法,即所传的参数为Map:

public String getData(String url,Map paramsMap){
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		//装配post请求参数
		List list = new ArrayList<>();
		for (String key : paramsMap.keySet()) {
			list.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
		}

		try {
			//将参数进行编码为合适的格式,如将键值对编码为param1=value1¶m2=value2
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
			httpPost.setEntity(urlEncodedFormEntity);

			//执行 post请求
			CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
			String strRequest = "";
			if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
				System.out.println(closeableHttpResponse.getStatusLine().getStatusCode());
				if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity httpEntity = closeableHttpResponse.getEntity();
					strRequest = EntityUtils.toString(httpEntity);
				} else {
					strRequest = "Error Response" + closeableHttpResponse.getStatusLine().getStatusCode();
				}
			}
			return strRequest;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "协议异常";
		} catch (ParseException e) {
			e.printStackTrace();
			return "解析异常";
		} catch (IOException e) {
			e.printStackTrace();
			return "传输异常";
		} finally {
			try {
				if (closeableHttpClient != null) {
					closeableHttpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

url就只为访问地址,把要传的参数封装到map中;上面的两种方法是固定的,直接拷贝过去,将需要的参数传进去即可,非常的方便

这里顺便说一下如何处理调用成功后返回回来的数据。
因为放回来的一般都是json格式的字符串,所以我们要将这个字符串解析成我们的想要的对象,那么就要用到上面的我们加入的fastjson依赖
方法如下:
如果是转为一个对象:

  String json = "{\"courseName\":\"空乘英语\",\"score\":\"1\"}";
        T t = JSONObject.parseObject(json, T.class);

如果是很多对象,我们就要转换为一个list

   String json = "[{\"courseName\":\"空乘英语\",\"score\":\"1\"},{\"courseName\":\"化学\",\"score\":\"2\"}]";
        List t = JSONArray.parseArray(json, T.class);

T就是我们要转的实体类:

  public class T {
        private String courseName;
        private String score;
	...
	...
	省略get/set
	...
	...
}


你可能感兴趣的:(HttpClient远程调用接口Post请求是所传参数为普通参数和Map)