HttpClient

HttpClient

常用的远程调用技术:

 1、socket 套接字  效率特别高   开发特麻烦

 2、Webservice     xml   传统公司使用比较多

 3、hessian

 4、httpClient  json  多用于互联网公司

 5、dubbo

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

HttpClient的使用
1.pom.xml
<dependencies>
   <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpclient</artifactId>
       <version>4.5.2</version>
   </dependency>
</dependencies>
2.Get请求
public class HttpClientGet {
   public static void main(String[] args) throws IOException {
       // 相当于打开浏览器
       CloseableHttpClient httpClient = HttpClients.createDefault();

       // 创建一个get的请求方式 不带参数
       // HttpGet httpGet = new HttpGet("http://www.chenqi.fun");

       // 创建一个get的请求方式 带参数
       HttpGet httpGet = new HttpGet("http://www.baidu.com/s?ie=UTF-8&wd=chenqi.fun");
     
       // 执行get请求
       CloseableHttpResponse response = httpClient.execute(httpGet);
       // 获取返回的数据
       // 200:正常
       // 404:找不到资源
       // 500:服务器内部错误
       // 400:参数问题
       // 302:重定向
       // 304:缓存
       // 403:Forbidden
       if (response.getStatusLine().getStatusCode() == 200) {
           String s = EntityUtils.toString(response.getEntity(), "UTF-8");
           System.out.println(s);
       }
   }
}
3.Post请求
public class HttpClientPost {
   public static void main(String[] args) throws IOException {
       // 相当于打开浏览器
       CloseableHttpClient httpClient = HttpClients.createDefault();

       // 创建一个post的请求方式 不带参数 有安全限制 这样打不开
       // HttpPost httpPost = new HttpPost("https://www.oschina.net/search");

       // https://www.oschina.net/search?scope=project&q=java
       // 创建一个post的请求方式 带参数
       HttpPost httpPost = new HttpPost("https://www.oschina.net/search");

       // 构建参数
       List<NameValuePair> params = new ArrayList<NameValuePair>();
       params.add(new BasicNameValuePair("scope","project"));
       params.add(new BasicNameValuePair("q","java"));
       params.add(new BasicNameValuePair("fromerr","GPsrlXzx"));
       // 把参数放入表单
       UrlEncodedFormEntity formEntity =new UrlEncodedFormEntity(params);
       // 把表单放入post请求中
       httpPost.setEntity(formEntity);

       // 模拟浏览器访问
       httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36");

       // 执行post请求
       CloseableHttpResponse response = httpClient.execute(httpPost);
       System.out.println(response.getStatusLine().getStatusCode());
       if (response.getStatusLine().getStatusCode() == 200) {
           String s = EntityUtils.toString(response.getEntity(), "UTF-8");
           System.out.println(s);
       }
   }
}
使用HttpClient工具类
public class HttpClient {
  private String url;
  private Map<String, String> param;
  private int statusCode;
  private String content;
  private String xmlParam;
  private boolean isHttps;

  public boolean isHttps() {
     return isHttps;
  }

  public void setHttps(boolean isHttps) {
     this.isHttps = isHttps;
  }

  public String getXmlParam() {
     return xmlParam;
  }

  public void setXmlParam(String xmlParam) {
     this.xmlParam = xmlParam;
  }

  public HttpClient(String url, Map<String, String> param) {
     this.url = url;
     this.param = param;
  }

  public HttpClient(String url) {
     this.url = url;
  }

  public void setParameter(Map<String, String> map) {
     param = map;
  }

  public void addParameter(String key, String value) {
     if (param == null)
        param = new HashMap<String, String>();
     param.put(key, value);
  }

  public void post() throws ClientProtocolException, IOException {
     HttpPost http = new HttpPost(url);
     setEntity(http);
     execute(http);
  }

  public void put() throws ClientProtocolException, IOException {
     HttpPut http = new HttpPut(url);
     setEntity(http);
     execute(http);
  }

  public void get() throws ClientProtocolException, IOException {
     if (param != null) {
        StringBuilder url = new StringBuilder(this.url);
        boolean isFirst = true;
        for (String key : param.keySet()) {
           if (isFirst)
              url.append("?");
           else
              url.append("&");
           url.append(key).append("=").append(param.get(key));
        }
        this.url = url.toString();
     }
     HttpGet http = new HttpGet(url);
     execute(http);
  }

  /**
   * set http post,put param
   */
  private void setEntity(HttpEntityEnclosingRequestBase http) {
     if (param != null) {
        List<NameValuePair> nvps = new LinkedList<NameValuePair>();
        for (String key : param.keySet())
           nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
        http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
     }
     if (xmlParam != null) {
        http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
     }
  }

  private void execute(HttpUriRequest http) throws ClientProtocolException,
        IOException {
     CloseableHttpClient httpClient = null;
     try {
        if (isHttps) {
           SSLContext sslContext = new SSLContextBuilder()
                 .loadTrustMaterial(null, new TrustStrategy() {
                    // 信任所有
                    public boolean isTrusted(X509Certificate[] chain,
                          String authType)
                          throws CertificateException {
                       return true;
                    }
                 }).build();
           SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                 sslContext);
           httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                 .build();
        } else {
           httpClient = HttpClients.createDefault();
        }
        CloseableHttpResponse response = httpClient.execute(http);
        try {
           if (response != null) {
              if (response.getStatusLine() != null)
                 statusCode = response.getStatusLine().getStatusCode();
              HttpEntity entity = response.getEntity();
              // 响应内容
              content = EntityUtils.toString(entity, Consts.UTF_8);
           }
        } finally {
           response.close();
        }
     } catch (Exception e) {
        e.printStackTrace();
     } finally {
        httpClient.close();
     }
  }

  public int getStatusCode() {
     return statusCode;
  }

  public String getContent() throws ParseException, IOException {
     return content;
  }

}
使用HttpClient工具类发送请求
public class HttpClientDemo {
   public static void main(String[] args) throws IOException, ParseException {
       HttpClient httpClient = new HttpClient("https://www.chenqi.fun");
       httpClient.get();
       String content = httpClient.getContent();
       System.out.println(content);

/*
*   HttpClient httpClient = new HttpClient("http://localhost:8081/brand/findPage");
//        int pageNo, int pageSize
       httpClient.addParameter("pageNo","1");
       httpClient.addParameter("pageSize","3");
       httpClient.post();
       String content = httpClient.getContent();
       System.out.println(content);
*/
   }
}


发表评论