Httpclient实现RPC

来源:互联网 发布:网络印刷系统多少钱 编辑:程序博客网 时间:2024/06/05 16:42
  • HttpClient简介
  • Get方法请求
  • Post方式请求
  • 通用类封装

一.HttpClient简介
HttpClient是Apache jakarta common下维护的子项目,封装在 commons-httpclient    jar包中,是一个能提供高效、功能丰富的支持http协议的客户端工具包,在java中的应用主要体现在模拟客户端请求,例如同其他系统或项目进行API数据的交互等,同时也是RPC的实现方式之一。为解决并发量大问题,建议升级到高版本,如4.0以上
maven项目直接引入jar依赖
        <!-- HttpClient依赖 -->        <dependency>            <groupId>commons-httpclient</groupId>            <artifactId>commons-httpclient</artifactId>            <version>3.1</version>        </dependency>

二.Get方式请求
Get方式请求主要分为以下步骤:
1、创建客户端
HttpClient  client = new HttpClient();
2、创建Get方式连接实例 
GetMethod  getMethod = new GetMethod(url);
3、execute方法执行方法实例 
client.executeMethod(getMethod);
4、读取响应response信息 
getMethod.getResponseBody()
5、处理获取到的response信息并释放连接 
method.releaseConnection();

三.Post方式请求
HttpClient基于post方式请求步骤基本同Get方式,除了
PostMethod method = new PostMethod(url);

四.通用类的封装(使用 MultiThreadedHttpConnectionManager类管理httpclient是为了解决多线程下并发访问的问题) 
public class HttpClientUtils {    private static Logger log = LoggerFactory.getLogger(HttpClientUtils.class);    private static final String ENCODING = "UTF-8";    private static final int CONNECTION_TIME_OUT = 3000;    private static final int SO_TIME_OUT = 5000;    private static final boolean STALE_CHECK_ENABLED = true;    private static final boolean TCP_NO_DELAY = true;    private static final int DEFAULT_MAX_CONNECTIONS_PER_HOST = 100;    private static final int MAX_TOTAL_CONNECTIONS = 1000;    private static final HttpConnectionManager connectionManager;    private static final HttpClient client;    static {        HttpConnectionManagerParams params = loadHttpConfFromFile();        connectionManager = new MultiThreadedHttpConnectionManager();        connectionManager.setParams(params);        client = new HttpClient(connectionManager);    }    private static HttpConnectionManagerParams loadHttpConfFromFile() {  //这几个参数很重要        HttpConnectionManagerParams params = new HttpConnectionManagerParams();        params.setConnectionTimeout(CONNECTION_TIME_OUT);  //连接超时时长        params.setStaleCheckingEnabled(STALE_CHECK_ENABLED);   //是否启用旧连接检查        params.setTcpNoDelay(TCP_NO_DELAY);        params.setSoTimeout(SO_TIME_OUT);                //读取数据超时时长        params.setDefaultMaxConnectionsPerHost(DEFAULT_MAX_CONNECTIONS_PER_HOST);  //由MultiThreadedHttpConnectionManager管理的最大连接数        params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);    //最大连接数        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));        return params;    }    public static String post(String url, String encoding, String content) {        try {            byte[] resp = post(url, content.getBytes(encoding));            if (null == resp)                return null;            return new String(resp, encoding);        } catch (UnsupportedEncodingException e) {            log.error(e.toString());            return null;        }    }    public static byte[] post(String url, byte[] content) {        try {            byte[] ret = post(url, new ByteArrayRequestEntity(content));            return ret;        } catch (Exception e) {            log.error(e.toString());            return null;        }    }    public static byte[] post(String url, RequestEntity requestEntity)            throws Exception {        PostMethod method = new PostMethod(url);           method.addRequestHeader("Connection", "Keep-Alive");              //这个参数也很重要        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));        method.setRequestEntity(requestEntity);        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");        try {            int statusCode = client.executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                return null;            }            return method.getResponseBody();        } catch (SocketTimeoutException e) {            log.error(e.toString());            return null;        } catch (Exception e) {            log.error(e.toString());            return null;        } finally {            if (method != null) {                method.releaseConnection();            }        }    }    public static String doPostByContentType(String url, String contentType, String content) throws Exception {        PostMethod method = new PostMethod(url);        method.addRequestHeader("Connection", "Keep-Alive");        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));        method.setRequestEntity(new ByteArrayRequestEntity(content.getBytes(ENCODING)));        method.addRequestHeader("Content-Type", contentType);        try {            int statusCode = client.executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                return null;            }            byte[] ret = method.getResponseBody();            if (ret == null)                return null;            return new String(ret, ENCODING);        } catch (SocketTimeoutException e) {            log.error(e.toString());            return null;        } catch (Exception e) {            log.error(e.toString());            return null;        } finally {            if (method != null) {                method.releaseConnection();            }        }    }    public static String doGet(String _url) {        try {            GetMethod getMethod = new GetMethod(_url);            client.executeMethod(getMethod);            return inputStream2String(getMethod.getResponseBodyAsStream());        } catch (Exception e) {            e.printStackTrace();            log.error(e.toString());            return null;        }    }    public static String doGetUrl(String _url) throws Exception {        GetMethod getMethod = new GetMethod(_url);        client.executeMethod(getMethod);        return inputStream2String(getMethod.getResponseBodyAsStream());    }    private static String inputStream2String(InputStream is) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(is));        StringBuffer buffer = new StringBuffer();        String line = "";        while ((line = in.readLine()) != null) {            buffer.append(line);        }        return buffer.toString();    }    private static String inputStream2String(InputStream is, String encoding) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(is, encoding));        StringBuffer buffer = new StringBuffer();        String line = "";        while ((line = in.readLine()) != null) {            buffer.append(line);        }        return buffer.toString();    }}
    //调用方
    StringBuilder sb = new StringBuilder("xxx.xxx.com");    sb.append("?applt=").append(applt).append("&token=").append(token);    HttpClientUtils.doGet(sb.toString());
使用httpclient一定要要根据实际项目场景正确设置上面那几个参数,不然会有风险的。如并发量大时连接池不够、请求等待等风险,这些是比较难测试出来的 .
原创粉丝点击