`
xysuxiaoguang
  • 浏览: 2420 次
社区版块
存档分类
最新评论

java

阅读更多
package com.Annual.Httpclient;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.CodingErrorAction;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.methods.HttpRequestBase;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;

/**
* 封装HttpClient
* <p>
*
*
* @Date 2016-8-11
*/
@SuppressWarnings("deprecation")
public class HttpClientWrapper {

private enum VERBTYPE {
GET, POST
}
//请求读取超时
private Integer socketTimeout = 3000;
//URL的连接等待超时时间
private Integer connectTimeout = 1000;
//连接池获取连接的超时时间
private Integer connectionRequestTimeout = 1000;

private static CloseableHttpClient client;
private RequestConfig requestConfig;
private List<ContentBody> contentBodies;
private List<NameValuePair> nameValuePostBodies;

private static PoolingHttpClientConnectionManager connManager = null;

static {
try {
SSLContext sslContext = SSLContexts.custom().useTLS().build();
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} }, null);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",new SSLConnectionSocketFactory(sslContext)).build();
connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
connManager.setDefaultSocketConfig(socketConfig);
MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints).build();
connManager.setDefaultConnectionConfig(connectionConfig);
//将最大连接数增加
connManager.setMaxTotal(200);
// 将每个路由基础的连接增加
connManager.setDefaultMaxPerRoute(80);
} catch (KeyManagementException e){
e.printStackTrace();
} catch (NoSuchAlgorithmException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}

// /**
// * 默认启用连接池技术
// * PoolingHttpClientConnectionManager
// * MaxTotal大小默认为200
// * socketTimeout 默认 3000
// * connectTimeout 默认 1000
// */
// public HttpClientWrapper() {
// super();
// client = HttpClients.custom().setConnectionManager(connManager).build();
// this.contentBodies = new ArrayList<ContentBody>();
// this.nameValuePostBodies = new LinkedList<NameValuePair>();
// this.requestConfig = RequestConfig.custom()
// .setConnectionRequestTimeout(this.connectionRequestTimeout)
// .setConnectTimeout(this.connectTimeout)
// .setSocketTimeout(this.socketTimeout).build();
// }

/**
*
* @param connectionRequestTimeout 连接池获取连接的超时时间
* @param connectTimeout 连接超时时间
* @param socketTimeout 读取超时时间
* @param isConnManager 是否使用连接池
*/
public HttpClientWrapper(Integer connectionRequestTimeout,Integer connectTimeout, Integer socketTimeout,boolean isConnManager) {
super();
this.socketTimeout = socketTimeout;
this.connectTimeout = connectTimeout;
this.connectionRequestTimeout = connectionRequestTimeout;

this.contentBodies = new ArrayList<ContentBody>();
this.nameValuePostBodies = new LinkedList<NameValuePair>();

if(isConnManager){
client = HttpClients.custom().setConnectionManager(connManager).build();
}else{
client = HttpClientBuilder.create().build();
}
this.requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(this.connectionRequestTimeout)
.setConnectTimeout(this.connectTimeout)
.setSocketTimeout(this.socketTimeout).build();
}

/**
* Get方式访问URL
* @param url
* @return ResponseContent
* @throws HttpException
* @throws IOException
*/
public ResponseContent getResponse(String url) throws HttpException,IOException {
return this.getResponse(url, "UTF-8", VERBTYPE.GET, null);
}

/**
* Get方式访问URL
* @param url
* @param urlEncoding 指定编码格式
* @return ResponseContent
* @throws HttpException
* @throws IOException
*/
public ResponseContent getResponse(String url, String urlEncoding) throws HttpException, IOException {
return this.getResponse(url, urlEncoding, VERBTYPE.GET, null);
}

/**
* POST方式发送名值对请求URL,默认Encoding为 UTF-8
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseContent postNV(String url) throws HttpException, IOException {
return this.getResponse(url, "UTF-8", VERBTYPE.POST, null);
}

/**
* POST方式发送名值对请求URL,默认Encoding为 UTF-8
* @param url
* @param contentType Content-Type 请参考 HTTP Content-type 对照表
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseContent postNV(String url, String contentType) throws HttpException, IOException {
return getResponse(url, "UTF-8", VERBTYPE.POST, contentType);
}

/**
* 根据url编码,请求方式,请求URL
*
* @param urlstr
* @param urlEncoding
* @param bodyType
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseContent getResponse(String urlstr, String urlEncoding,VERBTYPE bodyType, String contentType) throws HttpException,IOException {
if (urlstr == null)
return null;

String url = urlstr;
if (urlEncoding != null)
url = HttpClientWrapper.encodeURL(url.trim(), urlEncoding);

HttpEntity entity = null;
HttpRequestBase request = null;
CloseableHttpResponse response = null;
try {
if (VERBTYPE.GET == bodyType) {
request = new HttpGet(url);
} else if (VERBTYPE.POST == bodyType) {
this.parseUrl(url);
HttpPost httpPost = new HttpPost(toUrl());
List<NameValuePair> nvBodyList = this.getNVBodies();
httpPost.setEntity(new UrlEncodedFormEntity(nvBodyList, urlEncoding));
request = httpPost;
}

if (contentType != null) {
request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
request.setConfig(requestConfig);
request.addHeader(HttpHeaders.USER_AGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)");
response = client.execute(request);
entity = response.getEntity(); // 获取响应实体
StatusLine statusLine = response.getStatusLine();
ResponseContent responseContent = new ResponseContent();
responseContent.setStatusCode(statusLine.getStatusCode());
getResponseContent(entity, responseContent);
return responseContent;
} finally {
close(entity, request, response);
}
}

private void getResponseContent(HttpEntity entity, ResponseContent ret) throws IOException {
Header enHeader = entity.getContentEncoding();
if (enHeader != null) {
String charset = enHeader.getValue().toLowerCase();
ret.setEncoding(charset);
}
String contenttype = this.getResponseContentType(entity);
ret.setContentType(contenttype);
ret.setContentTypeString(this.getResponseContentTypeString(entity));
ret.setContentBytes(EntityUtils.toByteArray(entity));
}




public ResponseContent postEntity(String url) throws HttpException,IOException {
return this.postEntity(url, "UTF-8");
}

/**
* POST方式发送名值对请求URL,上传文件(包括图片)
*
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseContent postEntity(String url, String urlEncoding) throws HttpException, IOException {
if (url == null)
return null;

HttpEntity entity = null;
HttpRequestBase request = null;
CloseableHttpResponse response = null;
try {
this.parseUrl(url);
HttpPost httpPost = new HttpPost(toUrl());

// 对请求的表单域进行填充
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (NameValuePair nameValuePair : this.getNVBodies()) {
entityBuilder.addPart(nameValuePair.getName(),
new StringBody(nameValuePair.getValue(), ContentType.create("text/plain", urlEncoding)));
}
for (ContentBody contentBody : getContentBodies()) {
entityBuilder.addPart("file", contentBody);
}
entityBuilder.setCharset(CharsetUtils.get(urlEncoding));
httpPost.setEntity(entityBuilder.build());
request = httpPost;
response = client.execute(request);

// 响应状态
StatusLine statusLine = response.getStatusLine();
// 获取响应对象
entity = response.getEntity();
ResponseContent ret = new ResponseContent();
ret.setStatusCode(statusLine.getStatusCode());
getResponseContent(entity, ret);
return ret;
} finally {
close(entity, request, response);
}
}

private void close(HttpEntity entity, HttpRequestBase request, CloseableHttpResponse response) throws IOException {
if (request != null)
request.releaseConnection();
if (entity != null)
entity.getContent().close();
if (response != null)
response.close();
}

public NameValuePair[] getNVBodyArray() {
List<NameValuePair> list = this.getNVBodies();
if (list == null || list.isEmpty())
return null;
NameValuePair[] nvps = new NameValuePair[list.size()];
Iterator<NameValuePair> it = list.iterator();
int count = 0;
while (it.hasNext()) {
NameValuePair nvp = it.next();
nvps[count++] = nvp;
}
return nvps;
}

public List<NameValuePair> getNVBodies() {
return Collections.unmodifiableList(this.nameValuePostBodies);
}

private String getResponseContentType(HttpEntity method) {
Header contenttype = method.getContentType();
if (contenttype == null)
return null;
String ret = null;
try {
HeaderElement[] hes = contenttype.getElements();
if (hes != null && hes.length > 0) {
ret = hes[0].getName();
}
} catch (Exception e) {
}
return ret;
}

private String getResponseContentTypeString(HttpEntity method) {
Header contenttype = method.getContentType();
if (contenttype == null)
return null;
return contenttype.getValue();
}

static Set<Character> BEING_ESCAPED_CHARS = new HashSet<Character>();
static {
char[] signArray = { ' ', '\\', '‘', ']', '!', '^', '#', '`', '$', '{',
'%', '|', '}', '(', '+', ')', '<', '>', ';', '[' };
for (int i = 0; i < signArray.length; i++) {
BEING_ESCAPED_CHARS.add(new Character(signArray[i]));
}
}

public static String encodeURL(String url, String encoding) {
if (url == null)
return null;
if (encoding == null)
return url;

StringBuffer sb = new StringBuffer();
for (int i = 0; i < url.length(); i++) {
char c = url.charAt(i);
if (c == 10) {
continue;
} else if (BEING_ESCAPED_CHARS.contains(new Character(c))
|| c == 13 || c > 126) {
try {
sb.append(URLEncoder.encode(String.valueOf(c), encoding));
} catch (Exception e) {
sb.append(c);
}
} else {
sb.append(c);
}
}
return sb.toString().replaceAll("\\+", "%20");
}

private String protocol;
private String host;
private int port;
private String dir;
private String uri;
private final static int DefaultPort = 80;
private final static String ProtocolSeparator = "://";
private final static String PortSeparator = ":";
private final static String HostSeparator = "/";
private final static String DirSeparator = "/";

private void parseUrl(String url) {
this.protocol = null;
this.host = null;
this.port = DefaultPort;
this.dir = "/";
this.uri = dir;

if (url == null || url.length() == 0)
return;
String u = url.trim();
boolean MeetProtocol = false;
int pos = u.indexOf(ProtocolSeparator);
if (pos > 0) {
MeetProtocol = true;
this.protocol = u.substring(0, pos);
pos += ProtocolSeparator.length();
}
int posStartDir = 0;
if (MeetProtocol) {
int pos2 = u.indexOf(PortSeparator, pos);
int pos21 = u.indexOf(HostSeparator, pos);// 如果参数有日期格式(2015-04-20
// 18:27:17)需要做此判断
if (pos2 > 0 && pos21 > pos2) {
this.host = u.substring(pos, pos2);
pos2 = pos2 + PortSeparator.length();
int pos3 = u.indexOf(HostSeparator, pos2);
String PortStr = null;
if (pos3 > 0) {
PortStr = u.substring(pos2, pos3);
posStartDir = pos3;
} else {
int pos4 = u.indexOf("?");
if (pos4 > 0) {
PortStr = u.substring(pos2, pos4);
posStartDir = -1;
} else {
PortStr = u.substring(pos2);
posStartDir = -1;
}
}
try {
this.port = Integer.parseInt(PortStr);
} catch (Exception e) {
}
} else {
pos2 = u.indexOf(HostSeparator, pos);
if (pos2 > 0) {
this.host = u.substring(pos, pos2);
posStartDir = pos2;
} else {
this.host = u.substring(pos);
posStartDir = -1;
}
}

pos = u.indexOf(HostSeparator, pos);
pos2 = u.indexOf("?");
if (pos > 0 && pos2 > 0) {
this.uri = u.substring(pos, pos2);
} else if (pos > 0 && pos2 < 0) {
this.uri = u.substring(pos);
}
}

if (posStartDir >= 0) {
int pos2 = u.lastIndexOf(DirSeparator, posStartDir);
if (pos2 > 0) {
this.dir = u.substring(posStartDir, pos2 + 1);
}
}

}

private String toUrl() {
StringBuffer ret = new StringBuffer();
if (this.protocol != null) {
ret.append(this.protocol);
ret.append(ProtocolSeparator);
if (this.host != null)
ret.append(this.host);
if (this.port != DefaultPort) {
ret.append(PortSeparator);
ret.append(this.port);
}
}
ret.append(this.uri);
return ret.toString();
}

public void addNV(String name, String value) {
BasicNameValuePair nvp = new BasicNameValuePair(name, value);
this.nameValuePostBodies.add(nvp);
}

public void clearNVBodies() {
this.nameValuePostBodies.clear();
}

public List<ContentBody> getContentBodies() {
return contentBodies;
}
}
分享到:
评论

相关推荐

    Java 面经手册·小傅哥.pdf

    这是一本以面试题为入口讲解 Java 核心内容的技术书籍,书中内容极力的向你证实代码是对数学逻辑的具体实现。当你仔细阅读书籍时,会发现Java中有大量的数学知识,包括:扰动函数、负载因子、拉链寻址、开放寻址、...

    Java OCR 图像智能字符识别技术,可识别中文

    Java OCR(Optical Character Recognition,光学字符识别)技术是一种计算机视觉领域的应用,它能将图像中的文字转换成可编辑的文本格式。这项技术在各种场景下都有广泛应用,比如文档扫描、车牌识别、发票处理等。...

    java源码包2

    Applet钢琴模拟程序java源码 2个目标文件,提供基本的音乐编辑功能。编辑音乐软件的朋友,这款实例会对你有所帮助。 Calendar万年历 1个目标文件 EJB 模拟银行ATM流程及操作源代码 6个目标文件,EJB来模拟银行...

    java源码包3

    Applet钢琴模拟程序java源码 2个目标文件,提供基本的音乐编辑功能。编辑音乐软件的朋友,这款实例会对你有所帮助。 Calendar万年历 1个目标文件 EJB 模拟银行ATM流程及操作源代码 6个目标文件,EJB来模拟银行...

    java电商源代码 java电商源代码

    java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java电商源代码java...

    java api最新7.0

    JAVA开发人员最新版本7.0 api文档!本文档是 Java Platform Standard Edition 7 的 API !Java 1.7 API的中文帮助文档。 深圳电信培训中心 徐海蛟博士教学用api 7.0中文文档。支持全文检索,在线即时查询。 里面列...

    java景点导航系统java景点导航系统

    java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点导航系统java景点...

    java开源包4

    JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于...

    java开源包9

    JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于...

    java开源包8

    JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于...

    java开源包10

    JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于...

    Java2Pas Java代码转pas代码

    Java2Pas是一个实用工具,主要用于将Java编程语言编写的源代码转换为Pascal语言的等效代码。这个工具对于那些需要在两种语言之间迁移代码或者理解不同编程语言语法的开发者来说非常有价值。Java和Pascal虽然都是面向...

    java错误处理:java.lang.OutOfMemoryError: Java heap space

    ### Java 错误处理:java.lang.OutOfMemoryError: Java heap space 在Java应用程序开发过程中,经常遇到的一个问题就是内存溢出错误,特别是在处理大量数据或长时间运行的应用时。其中,“java.lang....

    Java文件管理系统源码.zip

    Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 Java文件管理系统源码 ...

    smali2java——直接将smali转换成java

    标题"smali2java——直接将smali转换成java"揭示了本文的核心主题,即一个名为"smali2java"的工具,它的主要功能是将编程语言Smali转换为Java。Smali是一种低级的、汇编式的语言,通常用于Android应用的逆向工程,而...

    java2python--java代码转python工具

    Java到Python的转换工具,如标题“java2python”所示,是编程领域中的一种实用技术,旨在帮助开发者将已有的Java代码转换为Python语言。这种转换对于那些熟悉Java但希望进入Python生态系统,或者想要利用Python特定...

    java开源包3

    JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于...

    java11安装包正式版

    jdk11官方版是一款专为java编程人员推出的软件开发工具。JAVA JDK 11最新版可以帮助用户轻松的获取到JAVA的运行环境,让你在电脑上进行程序开发操作。JAVA JDK 11软件新增Epsilon 垃圾收集器和lambda 参数的局部变量...

    Java1.6.0_26

    JDK(Java Development Kit)是Sun Microsystems针对Java开发员的产品。自从Java推出以来,JDK已经成为使用最广泛的Java SDK。JDK 是整个Java的核心,包括了Java运行环境,Java工具和Java基础的类库。JDK是学好Java的...

Global site tag (gtag.js) - Google Analytics