http之httpClient工具类

1.HttpProtocolHandler.java

package com.crs.ticket.utils.httpclient;import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.FilePartSource;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread;public class HttpProtocolHandler {private static String DEFAULT_CHARSET = "utf-8";/** 连接超时时间,由bean factory设置,缺省为8秒钟 */private int defaultConnectionTimeout = 8000;/** 回应超时时间, 由bean factory设置,缺省为60秒钟 */private int defaultSoTimeout = 2 * 60000;/** 闲置连接超时时间, 由bean factory设置,缺省为60秒钟 */private int defaultIdleConnTimeout = 60000;private int defaultMaxConnPerHost = 30;private int defaultMaxTotalConn = 80;/** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒 */private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;/*** HTTP连接管理器,该连接管理器必须是线程安全的.*/private HttpConnectionManager connectionManager;private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();/*** 工厂方法* * @return*/public static HttpProtocolHandler getInstance() {return httpProtocolHandler;}/*** 私有的构造方法*/private HttpProtocolHandler() {// 创建一个线程安全的HTTP连接池connectionManager = new MultiThreadedHttpConnectionManager();connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();ict.addConnectionManager(connectionManager);ict.setConnectionTimeout(defaultIdleConnTimeout);ict.start();}/*** 执行Http请求* * @param request* @return*/public HttpResponse execute(HttpRequest request) {HttpClient httpclient = new HttpClient(connectionManager);/*httpclient.getHostConfiguration().setProxy("10.199.75.12", 8080);UsernamePasswordCredentials creds = new UsernamePasswordCredentials("v_chenxuan", "abcd1234");  httpclient.getState().setProxyCredentials(AuthScope.ANY, creds);*/// 设置连接超时int connectionTimeout = defaultConnectionTimeout;if (request.getConnectionTimeout() > 0) {connectionTimeout = request.getConnectionTimeout();}httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);// 设置回应超时int soTimeout = defaultSoTimeout;if (request.getTimeout() > 0) {soTimeout = request.getTimeout();}httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);// 设置等待ConnectionManager释放connection的时间
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);String charset = request.getCharset();charset = charset == null ? DEFAULT_CHARSET : charset;HttpMethod method = null;if (request.getMethod().equals(HttpRequest.METHOD_GET)) {method = new GetMethod(request.getUrl());method.getParams().setCredentialCharset(charset);// parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
            method.setQueryString(request.getQueryString());} else {method = new PostMethod(request.getUrl());((PostMethod) method).addParameters(request.getParameters());method.addRequestHeader("Content-Type","application/x-www-form-urlencoded; text/html; charset="+ charset);//application/json//application/x-www-form-urlencoded
        }// 设置Http Header中的User-Agent属性method.addRequestHeader("User-Agent", "Mozilla/4.0");HttpResponse response = new HttpResponse();try {httpclient.executeMethod(method);if (request.getResultType().equals(HttpResultType.STRING)) {response.setStringResult(method.getResponseBodyAsString());} else if (request.getResultType().equals(HttpResultType.BYTES)) {response.setByteResult(method.getResponseBody());}response.setResponseHeaders(method.getResponseHeaders());} catch (UnknownHostException ex) {return null;} catch (IOException ex) {return null;} catch (Exception ex) {return null;} finally {method.releaseConnection();}return response;}/*** 执行Http请求* * @param request 请求数据* @param strParaFileName 文件类型的参数名* @param strFilePath 文件路径* @return * @throws HttpException, IOException */public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException {HttpClient httpclient = new HttpClient(connectionManager);// 设置连接超时int connectionTimeout = defaultConnectionTimeout;if (request.getConnectionTimeout() > 0) {connectionTimeout = request.getConnectionTimeout();}httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);// 设置回应超时int soTimeout = defaultSoTimeout;if (request.getTimeout() > 0) {soTimeout = request.getTimeout();}httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);// 设置等待ConnectionManager释放connection的时间
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);String charset = request.getCharset();charset = charset == null ? DEFAULT_CHARSET : charset;HttpMethod method = null;//get模式且不带上传文件if (request.getMethod().equals(HttpRequest.METHOD_GET)) {method = new GetMethod(request.getUrl());method.getParams().setCredentialCharset(charset);// parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
            method.setQueryString(request.getQueryString());} else if(strParaFileName.equals("") && strFilePath.equals("")) {//post模式且不带上传文件method = new PostMethod(request.getUrl());((PostMethod) method).addParameters(request.getParameters());method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset);}else {//post模式且带上传文件method = new PostMethod(request.getUrl());List<Part> parts = new ArrayList<Part>();for (int i = 0; i < request.getParameters().length; i++) {parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset));}//增加文件参数,strParaFileName是参数名,使用本地文件parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath))));// 设置请求体((PostMethod) method).setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));}// 设置Http Header中的User-Agent属性method.addRequestHeader("User-Agent", "Mozilla/4.0");HttpResponse response = new HttpResponse();try {httpclient.executeMethod(method);if (request.getResultType().equals(HttpResultType.STRING)) {response.setStringResult(method.getResponseBodyAsString());} else if (request.getResultType().equals(HttpResultType.BYTES)) {response.setByteResult(method.getResponseBody());}response.setResponseHeaders(method.getResponseHeaders());} catch (UnknownHostException ex) {return null;} catch (IOException ex) {return null;} catch (Exception ex) {return null;} finally {method.releaseConnection();}return response;}/*** 将NameValuePairs数组转变为字符串* * @param nameValues* @return*/protected String toString(NameValuePair[] nameValues) {if (nameValues == null || nameValues.length == 0) {return "null";}StringBuffer buffer = new StringBuffer();for (int i = 0; i < nameValues.length; i++) {NameValuePair nameValue = nameValues[i];if (i == 0) {buffer.append(nameValue.getName() + "=" + nameValue.getValue());} else {buffer.append("&" + nameValue.getName() + "="+ nameValue.getValue());}}return buffer.toString();}
}

2.HttpRequest.java

package com.crs.ticket.utils.httpclient;import org.apache.commons.httpclient.NameValuePair;public class HttpRequest {/** HTTP GET method */public static final String METHOD_GET = "GET";/** HTTP POST method */public static final String METHOD_POST = "POST";/*** 待请求的url*/private String url = null;/*** 默认的请求方式*/private String method = METHOD_POST;private int timeout = 0;private int connectionTimeout = 0;/*** Post方式请求时组装好的参数值对*/private NameValuePair[] parameters = null;/*** Get方式请求时对应的参数*/private String queryString = null;/*** 默认的请求编码方式*/private String charset = "utf-8";/*** 请求发起方的ip地址*/private String clientIp;/*** 请求返回的方式*/private HttpResultType resultType = HttpResultType.BYTES;public HttpRequest(HttpResultType resultType) {super();this.resultType = resultType;}/*** @return Returns the clientIp.*/public String getClientIp() {return clientIp;}/*** @param clientIp*            The clientIp to set.*/public void setClientIp(String clientIp) {this.clientIp = clientIp;}public NameValuePair[] getParameters() {return parameters;}public void setParameters(NameValuePair[] parameters) {this.parameters = parameters;}public String getQueryString() {return queryString;}public void setQueryString(String queryString) {this.queryString = queryString;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getMethod() {return method;}public void setMethod(String method) {this.method = method;}public int getConnectionTimeout() {return connectionTimeout;}public void setConnectionTimeout(int connectionTimeout) {this.connectionTimeout = connectionTimeout;}public int getTimeout() {return timeout;}public void setTimeout(int timeout) {this.timeout = timeout;}/*** @return Returns the charset.*/public String getCharset() {return charset;}/*** @param charset*            The charset to set.*/public void setCharset(String charset) {this.charset = charset;}public HttpResultType getResultType() {return resultType;}public void setResultType(HttpResultType resultType) {this.resultType = resultType;}}

3.HttpResponse.java

package com.crs.ticket.utils.httpclient;import java.io.UnsupportedEncodingException;import org.apache.commons.httpclient.Header;/***类名:HttpResponse*功能:Http返回对象的封装*详细:封装Http返回信息*版本:3.2*日期:2011-03-17*说明:*/public class HttpResponse {/*** 返回中的Header信息*/private Header[] responseHeaders;/*** String类型的result*/private String   stringResult;/*** btye类型的result*/private byte[]   byteResult;public Header[] getResponseHeaders() {return responseHeaders;}public void setResponseHeaders(Header[] responseHeaders) {this.responseHeaders = responseHeaders;}public byte[] getByteResult() {if (byteResult != null) {return byteResult;}if (stringResult != null) {return stringResult.getBytes();}return null;}public void setByteResult(byte[] byteResult) {this.byteResult = byteResult;}public String getStringResult() throws UnsupportedEncodingException {if (stringResult != null) {return stringResult;}if (byteResult != null) {return new String(byteResult, "utf-8");}return null;}public void setStringResult(String stringResult) {this.stringResult = stringResult;}}

4.HttpResultType.java

/*** Alipay.com Inc.* Copyright (c) 2004-2005 All Rights Reserved.*/
package com.crs.ticket.utils.httpclient;public enum HttpResultType {/*** 字符串方式*/STRING,/*** 字节数组方式*/BYTES
}

转载于:https://www.cnblogs.com/pypua/articles/7306944.html

http之httpClient工具类相关推荐

  1. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

  2. HttpClient工具类

    HttpClient工具类 package cn.sh.steven.httpclient;import com.alibaba.fastjson.JSON; import com.alibaba.f ...

  3. apache httpclient 工具类_HttpClient

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

  4. apache httpclient 工具类_HttpClient 和Mycat 主从节点和读写分离

    第175次(HttpClient) 学习主题:HttpClient 学习目标: 1 掌握HttpClient自定义工具以及HttpClient具体的使用 对应视频: http://www.itbaiz ...

  5. apache httpclient 工具类_使用HttpClient进行服务的远程调用

    目标:使用apache公司的产品http httpcomponents 完成服务调用. HTTPClient调用服务 4:导入httpclient的依赖配置 org.apache.httpcompon ...

  6. 使用单例模式实现自己的HttpClient工具类

    本文转载自:http://www.cnblogs.com/codingmyworld/archive/2011/08/17/2141706.html 使用单例模式实现自己的HttpClient工具类 ...

  7. 14、阿里云短信Demo演示、Http的Get请求和Post请求演示、httpClient工具类演示、发送短信模块搭建、搭建用户中心模块、完成user注册基本功能、验证码存入redis、短信验证码注册

    阿里云短信Demo演示 一.前端部分 无前端. 二.后端部分 1.创建发送短信测试模块SmsSendDemo,不用使用骨架. 2.在pom文件中引入依赖坐标 <dependency>< ...

  8. 工具类-httpClient工具类

    httpClient工具类 1.httpClient工具类(http/https.重发.超时.连接数的设置) package com.xxxxxxx.xxxx.xxxx.payutil;import ...

  9. HttpClient工具类封装

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

  10. HttpClient工具类及应用

    Content-Type类型: 常见的媒体格式类型如下: text/html : HTML格式 text/plain :纯文本格式 text/xml : XML格式 image/gif :gif图片格 ...

最新文章

  1. 计算机窗口还原,win8系统找回计算机窗口“回收站”的还原办法
  2. js中substr,substring,indexOf,lastIndexOf的用法
  3. 转:Object-Runtime的基本数据类型
  4. java)_Java NIO系列教程(一) Java NIO 概述
  5. 飞秋文件传输模拟实现代码
  6. jquery ajax调用服务器端指定的函数的三种方式
  7. 《恋上数据结构第1季》队列、双端队列、循环队列、循环双端队列
  8. [2017.01.04] 经典排序算法思想及其实现
  9. OpenGL纹理-12.5、纹理坐标
  10. electron打包exe文件
  11. 面向对象10:多态性的使用、重载和重写的区别、多态性的实用意义
  12. itools 苹果录屏大师 java_itools录屏大师使用常见问题_itools苹果录屏大师无法连接解决办法...
  13. 真无线蓝牙耳机哪个好?四款买了不亏的真无线蓝牙耳机
  14. ubuntu 安装postgresql 客户端 psql 以及运行相关命令
  15. Android 图片压缩也即生成缩略图方法
  16. 聚观早报 | 通信行程卡正式宣布下线;《三体》首日播放量破1亿
  17. 计算机作业攒机单,计算机攒机作业.docx
  18. MATLAB特殊矩阵的构造
  19. Cocos2d-x中图字原理之深入分析
  20. 计算机网络(第7版) - 第五章 运输层 - 习题

热门文章

  1. 人民币对美元汇率中间价报6.7592元 上调23个基点
  2. Android使用拖拽控件来布局界面并展示
  3. 实用ExtJS教程100例-001:开天辟地的Hello World
  4. python-unicode十进制数字转中文
  5. 循序渐进 OSPF的详细剖析(二)
  6. 一步一步学Silverlight 2系列(15):数据与通信之ASMX
  7. CGLIB实现AOP,MethodInterceptor接口和Enhancer详解——Spring AOP(四)
  8. springboot默认数据源如何设置连接数_Spring Boot学习:如何使用Druid数据源
  9. php 5分钟前,PHP实现时间轴函数(刚刚、5分钟前)
  10. java 驼峰自动映射_总结springboot开启mybatis驼峰命名自动映射的三种方式