首页 > Web开发 > 详细

配置httpclient

时间:2019-10-20 21:03:00      阅读:57      评论:0      收藏:0      [点我收藏+]

在分布式项目中,前端系统需要调用后台的数据并初始化时,可以使用httpclient通信器。先做一个测试

一、导入需要的依赖

<!-- httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
         版本为4.5.5
</dependency>

后台系统为manage_taotao,前端系统为web_taotao,设置的域名分别为manage.taotao.com 和web.taotao.com。在后台的一个test中写一个httpclient get请求

@Test
    public void getTestOne() {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet("http://localhost:8001/rest/test/doGetControllerOne");//controller层的测试地址
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)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));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

写一个post请求

@Test
    public void doPostTest() {
        CloseableHttpClient httpClient=HttpClientBuilder.create().build();
        try {
            URI uri=new URIBuilder("http://localhost:8001/rest/test/doGetControllerTwo").addParameter("name", "陈一峰")
                    .addParameter("age", "18").build();
            HttpPost post=new HttpPost(uri);
            CloseableHttpResponse response = httpClient.execute(post);
         // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    System.out.println("响应内容为:" + EntityUtils.toString(responseEntity,"utf-8"));
            }
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

json格式的post请求

@Test
    public void doPostEntityTest() {
        ObjectMapper mapper=new ObjectMapper();
        CloseableHttpClient httpClient=HttpClientBuilder.create().build();
        try {
            URI uri=new URIBuilder("http://manage.taotao.com/rest/test/doPostEntity").build();
            
            HttpPost post=new HttpPost(uri);
            User user=new User();
            user.setName("陈一峰");
            user.setAge(24);
            user.setSex(1);
            HttpEntity entity=new StringEntity(mapper.writeValueAsString(user),"utf-8");
            post.setHeader("Content-Type","application/json;charset=utf-8");
            post.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(post);
         // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    System.out.println("响应内容为:" + EntityUtils.toString(responseEntity,"utf-8"));
            }
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

这里controller层代码,@requestbody注解将json对象转化为java对象,不过使用很严格

@RequestMapping("doPostEntity")
    @ResponseBody
    public String test3(@RequestBody User user) {
        System.out.println(user);
        return "success";
    }

跟数据库的链接池类似,httpclient也提供了链接管理器来提高效率

@Test
    void test() {
        //创建一个链接管理器对象
       PoolingHttpClientConnectionManager cm=new PoolingHttpClientConnectionManager();
       cm.setMaxTotal(200);//最大连接对象个数
       cm.setDefaultMaxPerRoute(20);//最大路由个数
       getTestOne(cm);
       getTestOne(cm);
    }
    private void getTestOne(PoolingHttpClientConnectionManager cm) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(cm).build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet("http://localhost:8001/rest/test/doGetControllerOne");
        RequestConfig config=RequestConfig.custom().setConnectTimeout(1000)//请求地址的超时时间
                .setConnectionRequestTimeout(500)//从连接管理器中获取连接对象的超时时间
                .setSocketTimeout(10000).build();//传送数据的超时时间
        httpGet.setConfig(config);
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)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));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                //注意:httpClient不能关闭
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

在真正使用httpclient时,它的配置直接在xml中设置,部分代码抽取到公共service类里。

applicationContext-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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 创建连接管理器 -->
<bean id="connectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
    <!-- 最大连接对象个数 -->
    <property name="maxTotal" value="200"/>
    <!-- 最大路由个数 -->
    <property name="defaultMaxPerRoute" value="20"/>
</bean>

<!-- 创建httpclient工厂 -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
    <property name="connectionManager" ref="connectionManager"/>
</bean>
<!-- 创建一个httpclient对象 ,工厂模式-->
<bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype"></bean>

<!-- requestConfig设置,工厂模式 -->
<bean class="org.apache.http.client.config.RequestConfig" factory-bean="configBuilder"
factory-method="build"></bean>
<!-- 设置config的工厂 -->
<bean id="configBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
    <!-- 请求地址的超时时间 -->
    <property name="connectTimeout" value="1000"/>
    <!-- 从连接管理器中获取连接对象的超时时间 -->
    <property name="connectionRequestTimeout" value="500"/>
    <!-- 传送数据的超时时间 -->
    <property name="socketTimeout" value="10000"/>
</bean>
</beans>

抽取的ApiService

package com.taotao.web.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 java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.web.bean.HttpPostResult;

@Service
public class ApiService {
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private RequestConfig config;
    
    @Value(value="${manage_url}")
    public final String MANAGE_URL=null;//使用属性文件
    /**
     * get请求 无参
     * @param url
     * @return
     */
    public String doGet(String url) {
        HttpGet get=new HttpGet(url);
        get.setConfig(config);
        CloseableHttpResponse response=null;
        try {
            response=httpClient.execute(get);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(response!=null)
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }return null;
        
    }
    /**
     * get请求 有参
     * @param url
     * @param map
     * @return
     */
    public String doGetParam(String url,Map<String,Object> map) {
        List<NameValuePair> nvps=new ArrayList<NameValuePair>();
        for(Entry<String,Object> entry:map.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
        }
        CloseableHttpResponse response=null;
        try {
            URI uri=new URIBuilder(url).addParameters(nvps).build();
            HttpGet get=new HttpGet(uri);
            
            response=httpClient.execute(get);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
                
            }
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(response!=null)
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }return null;
    }
    /**
     * post请求 有参
     * @param url
     * @param map
     * @return
     */
    public HttpPostResult doPostParam(String url,Map<String,Object> map) {
        List<NameValuePair> nvps=new ArrayList<NameValuePair>();
        for(Entry<String,Object> entry:map.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
        }
        CloseableHttpResponse response=null;
        HttpPostResult result=null;
        try {
            URI uri=new URIBuilder(url).addParameters(nvps).build();
            HttpPost post=new HttpPost(uri);
            result=new HttpPostResult();
            response=httpClient.execute(post);
            result.setStatus(response.getStatusLine().getStatusCode());
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result.setData(EntityUtils.toString(responseEntity));
                
            }
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(response!=null)
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }return result;
    }
}

由apiservice得到的字符串数据一般为json字符串,用jackson之类的jar包解析即可

配置httpclient

原文:https://www.cnblogs.com/psxfd4/p/11708424.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!