HTTPCLIENT

1.   httpclient介绍

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

HttpClient和浏览器有点像,但不是浏览器,它是一个HTTP通信库,因此它只提供一个通用浏览器应用程序所期望的功能子集,最根本的区别是HttpClient中没有用户界面。

2.   快速使用httpclient

a)      引入jar包(Maven在pom.xml中引入HttpClient依赖)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>

  <artifactId>com-test</artifactId>

  <version>0.0.1-SNAPSHOT</version>

       <dependencies>

              <!-- httpclient -->

              <dependency>

                     <groupId>org.apache.httpcomponents</groupId>

                     <artifactId>httpclient</artifactId>

                     <version>4.3.5</version>

              </dependency>

              <!-- Jackson Json处理工具包 -->

              <dependency>

                     <groupId>com.fasterxml.jackson.core</groupId>

                     <artifactId>jackson-databind</artifactId>

                     <version>2.4.2</version>

              </dependency>

       </dependencies>

</project>

b)      get无参

       /**

        *   无参get

        */

       public static void testGet() {

              //1.通过HttpClientBuilder类的create方法创建HttpClientBuilder对象,再用HttpClientBuilder对象的builder方法创建closeableHttpClient对象;    相当于浏览器

              CloseableHttpClient closeableHttpClient=HttpClientBuilder.create().build();

              //2.创建httpGet对象   相当于在地址栏输入网址

              HttpGet httpGet=new HttpGet("http://127.0.0.1:7001/rest/user/list");

              CloseableHttpResponse httpResponse =null;

              try {

                     //3.通过closeableHttpClient对象的execute方法创建httpResponse对象    相当于按回车键(访问网址)

                     httpResponse = closeableHttpClient.execute(httpGet);

                    

                     System.out.println(EntityUtils.toString(httpResponse.getEntity()));

              } catch (IOException e) {

                     e.printStackTrace();

              }finally {

                     try {

                            if(httpResponse!=null) {

                                   httpResponse.close();

                            }

                            if(closeableHttpClient!=null) {

                                   closeableHttpClient.close();

                            }

                     } catch (IOException e) {

                            e.printStackTrace();

                     }

              }

       }

c)      get有参

       /**

        *   有参get

        */

       public static void testGetParams() {

              //1.通过HttpClientBuilder类的create方法创建HttpClientBuilder对象,再用HttpClientBuilder对象的builder方法创建closeableHttpClient对象;    相当于浏览器

              CloseableHttpClient closeableHttpClient=HttpClientBuilder.create().build();

              //2.创建httpGet对象   相当于在地址栏输入网址

//            HttpGet httpGet=new HttpGet("http://127.0.0.1:7001/rest/user/list?rows=1");//第一种方式.在地址上加?后跟参数

              CloseableHttpResponse httpResponse =null;

              try {

                     /*

                      * 第二种方式.通过URIBuilder类的add方法添加参数,在通过build方法得到uri对象

                      */

                     URI uri=new URIBuilder("http://127.0.0.1:7001/rest/user/list").addParameter("rows", "1").build();

                     HttpGet httpGet=new HttpGet(uri);

                    

                     //3.通过closeableHttpClient对象的execute方法创建httpResponse对象    相当于按回车键(访问网址)

                     httpResponse = closeableHttpClient.execute(httpGet);

                    

                     System.out.println(EntityUtils.toString(httpResponse.getEntity()));

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (URISyntaxException e) {

                     e.printStackTrace();

              }finally {

                     try {

                            if(httpResponse!=null) {

                                   httpResponse.close();

                            }

                            if(closeableHttpClient!=null) {

                                   closeableHttpClient.close();

                            }

                     } catch (IOException e) {

                            e.printStackTrace();

                     }

              }

       }

d)      post无参

       /**

        *   无参post

        */

       public static void testPost() {

              //1.通过HttpClientBuilder类的create方法创建HttpClientBuilder对象,再用HttpClientBuilder对象的builder方法创建closeableHttpClient对象;    相当于浏览器

              CloseableHttpClient closeableHttpClient=HttpClientBuilder.create().build();

              //2.创建httpPost对象  相当于在地址栏输入网址

              HttpPost httpPost=new HttpPost("http://127.0.0.1:7001/rest/user/list");

              CloseableHttpResponse httpResponse =null;

              try {

                     //3.通过closeableHttpClient对象的execute方法创建httpResponse对象    相当于按回车键(访问网址)

                     httpResponse = closeableHttpClient.execute(httpPost);

                    

                     System.out.println(EntityUtils.toString(httpResponse.getEntity()));

              } catch (IOException e) {

                     e.printStackTrace();

              }finally {

                     try {

                            if(httpResponse!=null) {

                                   httpResponse.close();

                            }

                            if(closeableHttpClient!=null) {

                                   closeableHttpClient.close();

                            }

                     } catch (IOException e) {

                            e.printStackTrace();

                     }

              }

       }

e)      post简单(基本类型,string,数组)参

       /**

        *   简单参post

        */

       public static void testPostParams() {

              //1.通过HttpClientBuilder类的create方法创建HttpClientBuilder对象,再用HttpClientBuilder对象的builder方法创建closeableHttpClient对象;    相当于浏览器

              CloseableHttpClient closeableHttpClient=HttpClientBuilder.create().build();

              //2.创建httpGet对象   相当于在地址栏输入网址

//            HttpPost httpPost=new HttpPost("http://127.0.0.1:7001/rest/user/list?rows=1");//第一种方式.在地址上加?后跟参数

              CloseableHttpResponse httpResponse =null;

              try {

                     /*

                      * 第二种方式.通过URIBuilder类的add方法添加参数,在通过build方法得到uri对象

                      */

                     URI uri=new URIBuilder("http://127.0.0.1:7001/rest/user/list").addParameter("ids", "1,2").build();//addParameter("ids", "1,2")传出去的是个数组

                     HttpPost httpPost=new HttpPost(uri);

                    

                     //3.通过closeableHttpClient对象的execute方法创建httpResponse对象    相当于按回车键(访问网址)

                     httpResponse = closeableHttpClient.execute(httpPost);

                    

                     System.out.println(EntityUtils.toString(httpResponse.getEntity()));

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (URISyntaxException e) {

                     e.printStackTrace();

              }finally {

                     try {

                            if(httpResponse!=null) {

                                   httpResponse.close();

                            }

                            if(closeableHttpClient!=null) {

                                   closeableHttpClient.close();

                            }

                     } catch (IOException e) {

                            e.printStackTrace();

                     }

              }

       }

f)       post简单参+对象:控制层接收的对象前一定要加注解@RequestBody,否则报错415

       /**

        *   对象+简单参post

        */

       public static void testPostParam() {

              ObjectMapper objectMapper=new ObjectMapper();//json字符串和java对象互转

              //1.通过HttpClientBuilder类的create方法创建HttpClientBuilder对象,再用HttpClientBuilder对象的builder方法创建closeableHttpClient对象;    相当于浏览器

              CloseableHttpClient closeableHttpClient=HttpClientBuilder.create().build();

              //2.创建httpGet对象   相当于在地址栏输入网址

              CloseableHttpResponse httpResponse =null;

              try {

                     /*

                      * 第一种方式.通过URIBuilder类的add方法添加参数,在通过build方法得到uri对象

                      */

                     URI uri=new URIBuilder("http://127.0.0.1:7001/rest/user/list").addParameter("ids", "1,2").build();//addParameter("ids", "1,2")传出去的是个数组

                     HttpPost httpPost=new HttpPost(uri);

                     //创建user对象

                     User user=new User(null, "测试", null, null, null, null, null, null, null);

                     //把user对象转成json字符串放到创建的StringEntity对象里,然后再用httpPost对象添加对象

                     httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(user),"utf-8"));

                    

                     //一定要设置http头部信息

                     httpPost.setHeader("Content-Type", "application/json;charset=utf8");

                    

                     //3.通过closeableHttpClient对象的execute方法创建httpResponse对象    相当于按回车键(访问网址)

                     httpResponse = closeableHttpClient.execute(httpPost);

                    

                     System.out.println(EntityUtils.toString(httpResponse.getEntity()));

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (URISyntaxException e) {

                     e.printStackTrace();

              }finally {

                     try {

                            if(httpResponse!=null) {

                                   httpResponse.close();

                            }

                            if(closeableHttpClient!=null) {

                                   closeableHttpClient.close();

                            }

                     } catch (IOException e) {

                            e.printStackTrace();

                     }

              }

       }

g)      连接管理器PoolHttpClientConnectionManager和请求配置器RequestConfig

       /**

        *   1.连接管理器PoolingHttpClientConnectionManager,2.请求配置RequestConfig

        */

       public static void testPoolAndConfig() {

              //1.创建连接管理器PoolingHttpClientConnectionManager

              PoolingHttpClientConnectionManager cm=new PoolingHttpClientConnectionManager();

              cm.setMaxTotal(10);//设置最大连接数

              cm.setDefaultMaxPerRoute(5);//设置最大路由数

              doGet(cm);

              doGet(cm);

             

       }

       public static void doGet(PoolingHttpClientConnectionManager cm) {

              //通过HttpClients的custom方法获得HttpClientBuilder对象,在用setConnectionManager方法设置连接管理器,再用build创建closeableHttpClient对象

              CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(cm).build();

              HttpGet httpGet=new HttpGet("http://127.0.0.1:7001/rest/user/list?rows=1");

             

              //2.配置requestConfig

              RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(5000)//设置连接最大时间

                            .setConnectionRequestTimeout(3000)//设置连接请求最大时间

                            .setSocketTimeout(2000).build();//设置传输最大时间

              httpGet.setConfig(requestConfig);//把requestConfig设置到httpGet对象里

             

              CloseableHttpResponse httpResponse =null;

              try {

                     httpResponse=closeableHttpClient.execute(httpGet);

                     System.out.println(EntityUtils.toString(httpResponse.getEntity()));

              } catch (IOException e) {

                     e.printStackTrace();

              }finally {

                     try {

                            if(httpResponse!=null) {

                                   httpResponse.close();

                            }

//                          if(closeableHttpClient!=null) {

//                                 closeableHttpClient.close();//一定不能close,否则报错:Exception in thread "main" java.lang.IllegalStateException: Connection pool shut down

//                          }

                     } catch (IOException e) {

                            e.printStackTrace();

                     }

              }

       }

Spring和HttpClient整合(spring和httpclient的配置文件,httpclient的公共ApiService)

1.spring和httpclient配置文件:applicationContent-httpclient.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

      

       <!-- 配置连接管理器 -->

       <bean id="cm" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">

              <property name="maxTotal" value="200"/>

              <property name="defaultMaxPerRoute" value="50"/>

       </bean>

      

       <!-- 配置HttpClientBuilder用来创建CloseableHttpClient对象 -->

       <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">

              <property name="connectionManager" ref="cm"/>

       </bean>

       <!-- 创建CloseableHttpClient对象 -->

       <bean id="closeableHttpClient" class="org.apache.http.impl.client.CloseableHttpClient" factory-bean="httpClientBuilder" factory-method="build" scope="prototype">

       </bean>

      

       <!-- 配置Builder对象来获得RequestConfig对象 -->

       <bean id="builder" class="org.apache.http.client.config.RequestConfig.Builder">

              <property name="connectTimeout" value="5000"/>

              <property name="connectionRequestTimeout" value="3000"/>

              <property name="socketTimeout" value="2000"/>

       </bean>

       <bean id="requestConfig" class="org.apache.http.client.config.RequestConfig" factory-bean="builder" factory-method="build">

       </bean>

</beans>

2.公共的ApiService接口和实现类

ApiService接口:

package com.zhiyou100.kfs.service;

import java.util.Map;

import com.zhiyou100.kfs.bean.HttpResult;

public interface ApiService {

      

       /**

        *   无参get

        * @param url

        */

       String doGet(String url);

      

       /**

        *   有参get

        * @param url

        * @param map

        * @return

        */

       String doGet(String url,Map<String, Object> map);

      

       /**

        *   无参post

        * @param url

        * @return

        */

       String doPost(String url);

      

       /**

        *   有参post

        * @param url

        * @param map

        * @return

        */

       HttpResult doPost(String url,Map<String, Object> map);

}

接口实现类ApiServiceImp:

package com.zhiyou100.kfs.service;

import java.io.IOException;

import java.net.URI;

import java.net.URISyntaxException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.http.NameValuePair;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.URIBuilder;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.zhiyou100.kfs.bean.HttpResult;

/**

 *   把httpclient抽取出来

 * @author KFS

 *

 */

@Service

public class ApiServiceImp implements ApiService{

       @Autowired

       private CloseableHttpClient closeableHttpClient;

       @Autowired

       private RequestConfig requestConfig;

      

       /**

        *   无参get

        * @param url

        */

       public String doGet(String url) {

              HttpGet httpGet=new HttpGet(url);

              httpGet.setConfig(requestConfig);

             

              CloseableHttpResponse httpResponse =null;

              try {

                     httpResponse = closeableHttpClient.execute(httpGet);

                     if(httpResponse!=null&&httpResponse.getStatusLine().getStatusCode()==200) {

                            return EntityUtils.toString(httpResponse.getEntity(),"utf-8");

                     }

              } catch (IOException e) {

                     e.printStackTrace();

              }

              return null;

       }

      

       /**

        *   有参get

        * @param url

        * @param map

        * @return

        */

       public String doGet(String url,Map<String, Object> map) {

              List<NameValuePair> nvps=new ArrayList<>();

              if(!map.isEmpty()) {

                     for(String key:map.keySet()) {

                            NameValuePair nvp=new BasicNameValuePair(key, map.get(key).toString());

                            nvps.add(nvp);

                     }

              }

             

              CloseableHttpResponse httpResponse =null;

              try {

                     URI uri=new URIBuilder(url).addParameters(nvps).build();

                     HttpGet httpGet=new HttpGet(uri);

                     httpGet.setConfig(requestConfig);

                    

                     httpResponse = closeableHttpClient.execute(httpGet);

                     if(httpResponse!=null&&httpResponse.getStatusLine().getStatusCode()==200) {

                            return EntityUtils.toString(httpResponse.getEntity(),"utf-8");

                     }

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (URISyntaxException e) {

                     e.printStackTrace();

              }

              return null;

       }

      

       /**

        *   无参post

        * @param url

        * @return

        */

       public String doPost(String url) {

              HttpPost httpPost=new HttpPost(url);

              httpPost.setConfig(requestConfig);

             

              CloseableHttpResponse httpResponse =null;

              try {

                     httpResponse = closeableHttpClient.execute(httpPost);

                     if(httpResponse!=null&&httpResponse.getStatusLine().getStatusCode()==200) {

                            return EntityUtils.toString(httpResponse.getEntity(),"utf-8");

                     }

              } catch (IOException e) {

                     e.printStackTrace();

              }

              return null;

       }

      

       /**

        *   有参post

        * @param url

        * @param map

        * @return

        */

       public HttpResult doPost(String url,Map<String, Object> map) {

              List<NameValuePair> nvps=new ArrayList<>();

              if(!map.isEmpty()) {

                     for(String key:map.keySet()) {

                            NameValuePair nvp=new BasicNameValuePair(key, map.get(key).toString());

                            nvps.add(nvp);

                     }

              }

             

              CloseableHttpResponse httpResponse =null;

              try {

                     URI uri=new URIBuilder(url).addParameters(nvps).build();

                     HttpPost httpPost=new HttpPost(uri);

                     httpPost.setConfig(requestConfig);

                    

                     httpResponse = closeableHttpClient.execute(httpPost);

                     if(httpResponse!=null&&httpResponse.getStatusLine().getStatusCode()==200) {

                            return new HttpResult(httpResponse.getStatusLine().getStatusCode(),EntityUtils.toString(httpResponse.getEntity(),"utf-8"));

                     }

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (URISyntaxException e) {

                     e.printStackTrace();

              }

              return null;

       }

}

原文地址:https://www.cnblogs.com/kfsrex/p/11704282.html