运用HttpClient调用其它项目的接口


首先引入依赖

    <dependency>
      <groupId>org.apache.httpcomponentsgroupId>
      <artifactId>httpclientartifactId>
      <version>4.5.6version>
    dependency>
private final int timeOut = 500;
public
String queryString(String code) { // 获得Http客户端(可以理解为:先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数 StringBuffer params = new StringBuffer(); try { // 字符数据最好encoding下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去) params.append("code=" + URLEncoder.encode(code, "utf-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 创建Get请求 HttpGet httpGet = new HttpGet(192.168.xx.xx:port/xx/queryString); // 响应模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(timeOut) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(timeOut) // socket读写超时时间(单位毫秒) .setSocketTimeout(timeOut) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里 httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); String json = EntityUtils.toString(responseEntity); String result = JsonUtil.fromJson(json, String.class); if(null!= result ){ return result ; } } else { return null; } } catch (Exception e) { //todo 此处做异常处理返回 //e.printStackTrace();return ("与数据服务连接异常!"); } finally { closeClient(httpClient, response); } return null; }