/**
*
*/
package com.bycm.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* @author jinyulinlang date:2018年7月18日
*/
public class HttpInvoker {
private static HttpInvoker httpInvoker = new HttpInvoker();
//
private HttpClient httpClient = null;
// 编码格式
private String charset = "gbk";
// 请求超时时间
private int timeout = 10000;
private int connecTimeout = 10000;
// 是否使用代理服务器
private boolean useProxy = false;
// 代理服务器主机域名
private String proxyHost = null;
// 代理服务器端口号
private int proxyPort;
// 代理服务器用户的名称
private String proxyUsername = null;
// 代理服务器用户的密码
private String proxyPassword = null;
// 是否已经被初始化
private boolean initialized = false;
// 简单工厂实例化
public static HttpInvoker getInstance() {
return httpInvoker;
}
/**
* 无参构造
*/
private HttpInvoker() {
httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
httpClient.getParams().setParameter("http.protocol.content-charset", "gbk");
httpClient.getParams().setContentCharset("gbk");
httpClient.getParams().setSoTimeout(timeout);
}
/**
* 带参构造
*
* @param charset
* 编码格式
* @param timeout
* 过期时间
* @param useProxy
* 是否代理服务器
* @param proxyHost
* 代理服务器
* @param proxyPort
* 服务器端口号
* @param proxyUsername
* 代理服务器用户名
* @param proxyPassword
* 代理服务器密码
*/
public HttpInvoker(String charset, int timeout, boolean useProxy, String proxyHost, int proxyPort,
String proxyUsername, String proxyPassword) {
httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
// 付过编码格式不为空
if (charset != null && !charset.trim().equals("")) {
this.charset = charset;
}
// 如果过期时间
if (timeout > 0) {
this.timeout = timeout;
}
/************ 实验 *************/
// 对请求信息头部的设置
/************ 实验 *************/
// 设置请求协议的编码格式
httpClient.getParams().setParameter("http.protocol.content-charset", charset);
// 设置内容的编码格式
httpClient.getParams().setContentCharset(charset);
// 设置链接超时
httpClient.getParams().setConnectionManagerTimeout(connecTimeout);
// 请求超时
httpClient.getParams().setSoTimeout(timeout);
// 如果使用代理服务器的话代理服务器不为空或者服务器端口大于0
if (useProxy && proxyHost != null && !proxyHost.trim().equals("") && proxyPort > 0) {
// 声明一个主机配置类
HostConfiguration hc = new HostConfiguration();
hc.setProxy(proxyHost, proxyPort);
httpClient.setHostConfiguration(hc);
if (proxyUsername != null && !proxyUsername.trim().equals("") && proxyPassword != null
&& !proxyPassword.trim().equals("")) {
httpClient.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUsername, proxyPassword));
}
}
initialized = true;
}
public void setCharset(String charset) {
this.charset = charset;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
public void setUseProxy(boolean useProxy) {
this.useProxy = useProxy;
}
public synchronized boolean isInitialized() {
return initialized;
}
/**
*
*/
public synchronized void init() {
if (charset != null && !charset.trim().equals("")) {
httpClient.getParams().setParameter("http.protocol.content-charset", charset);
httpClient.getParams().setContentCharset(charset);
}
if (timeout > 0) {
httpClient.getParams().setSoTimeout(timeout);
}
if (useProxy && proxyHost != null && !proxyHost.trim().equals("") && proxyPort > 0) {
HostConfiguration hc = new HostConfiguration();
hc.setProxy(proxyHost, proxyPort);
httpClient.setHostConfiguration(hc);
if (proxyUsername != null && !proxyUsername.trim().equals("") && proxyPassword != null
&& !proxyPassword.trim().equals("")) {
httpClient.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUsername, proxyPassword));
}
}
initialized = true;
}
/**
* 无参请求
*
* @param url
* @return
* @throws Exception
*/
public String invoke(String url) throws Exception {
return invoke(url, null, false);
}
/**
*
* @param url
* 请求路径
* @param params
* 请求携带的参数
* @param isPost
* 是否使用post请求
* @return
* @throws IOException
*/
public String invoke(String url, Map<String, Object> params, boolean isPost) throws IOException {
HttpMethod httpMethod = null;
String result = "";
if (isPost && params != null && params.size() > 0) {
Iterator<String> paramKeys = params.keySet().iterator();
httpMethod = new PostMethod(url);
NameValuePair[] nvp = new NameValuePair[params.size()];
int count = 0;
while (paramKeys.hasNext()) {
String key = (String) paramKeys.next();
Object value = params.get(key);
if (value != null && value instanceof String && !value.equals("")) {
nvp[count] = new NameValuePair(key, (String) value);
count++;
} else if (value != null && value instanceof String[] && ((String[]) value).length > 0) {
NameValuePair[] tempNvp = new NameValuePair[nvp.length + ((String[]) value).length - 1];
for (int i = 0; i < count; i++) {
tempNvp[i] = nvp[i];
}
nvp = tempNvp;
for (String v : (String[]) value) {
nvp[count] = new NameValuePair(key, (String) v);
count++;
}
}
}
((PostMethod) httpMethod).setRequestBody(nvp);
} else {
if (params != null && params.size() > 0) {
Iterator<String> paramKeys = params.keySet().iterator();
StringBuffer getUrl = new StringBuffer(url.trim());
if (url.trim().indexOf("?") > -1) {
if (url.trim().indexOf("?") < url.trim().length() - 1
&& url.trim().indexOf("&") < url.trim().length() - 1) {
getUrl.append("&");
}
} else {
getUrl.append("?");
}
while (paramKeys.hasNext()) {
String key = paramKeys.next();
Object value = params.get(key);
if (value != null && value instanceof String && !value.equals("")) {
getUrl.append(key).append("=").append(value).append("&");
} else if (value != null && value instanceof String[] && ((String[]) value).length > 0) {
for (String v : (String[]) value) {
getUrl.append(key).append("=").append(v).append("&");
}
}
}
// 如果get请求的url最后一个字符是&则把他给去掉
if (getUrl.lastIndexOf("&") == getUrl.length() - 1) {
httpMethod = new GetMethod(getUrl.substring(0, getUrl.length() - 1));
} else {
httpMethod = new GetMethod(getUrl.toString());
}
} else {
httpMethod = new GetMethod(url);
}
httpClient.executeMethod(httpMethod);
result = httpMethod.getResponseBodyAsString();
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpMethod.getResponseBodyAsStream(), charset));
String line = null;
String html = null;
while ((line = reader.readLine()) != null) {
if (html == null) {
html = "";
} else {
html += "\r\n";
}
html += line;
}
if (html != null) {
result = new String(html.getBytes(charset), charset);
}
}
// 释放链接
httpMethod.releaseConnection();
return result;
}
}