import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.httpclient. * ;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod; import java.util.Iterator;
import java.util.Map;
import java.net.SocketTimeoutException;
import java.io.BufferedReader;
import java.io.InputStreamReader; public class HttpInvoker {
private Log logger = LogFactory.getLog(HttpInvoker.class);
private static HttpInvoker httpInvoker = new HttpInvoker();
private HttpClient client = null;
private String charset = "gbk";
private int timeout = 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() {
client = new HttpClient(new MultiThreadedHttpConnectionManager());
client.getParams().setParameter("http.protocol.content-charset", "gbk");
client.getParams().setContentCharset("gbk");
client.getParams().setSoTimeout(timeout);
} public HttpInvoker(String charset, int timeout, boolean useProxy,
String proxyHost, int proxyPort, String proxyUsername,
String proxyPassword) {
client = new HttpClient(new MultiThreadedHttpConnectionManager());
if (charset != null && !charset.trim().equals("")) {
this.charset = charset;
}
if (timeout > 0) {
this.timeout = timeout;
}
client.getParams().setParameter("http.protocol.content-charset", charset);
client.getParams().setContentCharset(charset);
client.getParams().setSoTimeout(timeout);
if (useProxy && proxyHost != null &&
!proxyHost.trim().equals("") && proxyPort > 0) {
HostConfiguration hc = new HostConfiguration();
hc.setProxy(proxyHost, proxyPort);
client.setHostConfiguration(hc);
if (proxyUsername != null && !proxyUsername.trim().equals("") &&
proxyPassword != null && !proxyPassword.trim().equals("")) {
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUsername, proxyPassword));
}
}
initialized = true;
logger.debug("HttpInvoker初始化完成");
} public synchronized void init() {
if (charset != null && !charset.trim().equals("")) {
client.getParams().setParameter("http.protocol.content-charset", charset);
client.getParams().setContentCharset(charset);
}
if (timeout > 0) {
client.getParams().setSoTimeout(timeout);
}
if (useProxy && proxyHost != null &&
!proxyHost.trim().equals("") && proxyPort > 0) {
HostConfiguration hc = new HostConfiguration();
hc.setProxy(proxyHost, proxyPort);
client.setHostConfiguration(hc);
if (proxyUsername != null && !proxyUsername.trim().equals("") &&
proxyPassword != null && !proxyPassword.trim().equals("")) {
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUsername, proxyPassword));
}
}
initialized = true;
logger.debug("HttpInvoker初始化完成");
} public String invoke(String url)throws Exception {
return invoke(url, null, false);
} public String invoke(String url, Map params, boolean isPost)throws Exception {
logger.debug("HTTP调用[" + (isPost ? "POST" : "GET") + "][" + url + "][" + params + "]");
HttpMethod httpMethod = null;
String result = "";
try {
if (isPost && params != null && params.size() > 0) {
Iterator paramKeys = params.keySet().iterator();
httpMethod = new PostMethod(url);
NameValuePair[]form = new NameValuePair[params.size()];
int formIndex = 0;
while (paramKeys.hasNext()) {
String key = (String)paramKeys.next();
Object value = params.get(key);
if (value != null && value instanceof String && !value.equals("")) {
form[formIndex] = new NameValuePair(key, (String)value);
formIndex++;
} else if (value != null && value instanceof String[] &&
((String[])value).length > 0) {
NameValuePair[]tempForm =
new NameValuePair[form.length + ((String[])value).length - 1];
for (int i = 0; i < formIndex; i++) {
tempForm[i] = form[i];
}
form = tempForm;
for (String v : (String[])value) {
form[formIndex] = new NameValuePair(key, (String)v);
formIndex++;
}
}
}
((PostMethod)httpMethod).setRequestBody(form);
} else {
if (params != null && params.size() > 0) {
Iterator 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 = (String)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("&");
}
}
}
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);
}
}
client.executeMethod(httpMethod);
// result = httpMethod.getResponseBodyAsString();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpMethod.getResponseBodyAsStream(), "ISO-8859-1"));
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("ISO-8859-1"), charset);
}
} catch (SocketTimeoutException e) {
logger.error("连接超时[" + url + "]");
throw e;
}
catch (java.net.ConnectException e) {
logger.error("连接失败[" + url + "]");
throw e;
}
catch (Exception e) {
logger.error("连接时出现异常[" + url + "]");
throw e;
}
finally {
if (httpMethod != null) {
try {
httpMethod.releaseConnection();
} catch (Exception e) {
logger.error("释放网络连接失败[" + url + "]");
throw e;
}
}
} return result;
} 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;
}
}

使用方式:post

Map<String,String> params = new HashMap<String,String>();
params.put("check", check);
String result = httpInvoker.invoke( "someURL", params, true);

使用方式:get

String content  = httpInvoker.invoke(url);

HttpClient使用学习的更多相关文章

  1. HttpClient研究学习总结

    Http协议非常的重要,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人 ...

  2. Httpclient的学习(一)

    1.名词解释 抓包: 抓包(packet capture)就是将网络传输发送与接收的数据包进行截获.重发.编辑.转存等操作,也用来检查网络安全.抓包也经常被用来进行数据截取等. Httpclient: ...

  3. HttpClient&&RestTemplate学习

    1. 什么是HttpClient HttpClient是Apache下面的子项目,可以提供高效的,最新的,功能丰富的支持HTTP协议的客户端编程工具包. 2. 为什么要学习HttpClient Htt ...

  4. 【HttpClient】使用学习

    HttpClient使用学习 HttpClient Tutorial:http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/in ...

  5. android通过HttpClient与服务器JSON交互

    通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; i ...

  6. HttpClient客户端网络编程——高可用、高并发

    本文是HttpClient的学习博客,RestTemplate是基于HttpClient的封装,feign可基于HttpClient进行网络通信. 那么作为较底层的客户端网络编程框架,该怎么配置使其能 ...

  7. 在ASP dot Net Core MVC中用Controllers调用你的Asp dotnet Core Web API 实现CRUD到远程数据库中,构建你的分布式应用(附Git地址)

    本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...

  8. 在Core环境下用WebRequest连接上远程的web Api 实现数据的简单CRUD(附Git地址)

    本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...

  9. System.Net.Http

    System.Net.Http DotNet菜园 占个位置^-^ 2018-11-10 09:55:00修改 这个HttpClient的学习笔记一直迟迟未记录,只引用了其他博主的博客链接占个位置,但被 ...

随机推荐

  1. 转:sock_ev——linux平台socket事件框架(logTrace) .

    写代码要有调试log,采用syslog的输出:一般会输出到"/var/log/messages" /**************************************** ...

  2. Node.js 使用JWT进行用户认证

    代码地址如下:http://www.demodashi.com/demo/13847.html 运行环境 该项目基于 node(v7.8.0版本以上) 和 mongodb 数据库,因此电脑上需要安装这 ...

  3. LaTeX去掉默认显示日期时间

    LaTeX去掉默认显示日期时间: \date{}

  4. 迭代器类vector::iterator 和 vector::reverse_iterator 的实现、迭代器类型、常用的容器成员

    一.迭代器 迭代器是泛型指针 普通指针可以指向内存中的一个地址 迭代器可以指向容器中的一个位置 STL的每一个容器类模版中,都定义了一组对应的迭代器类.使用迭代器,算法函数可以访问容器中指定位置的元素 ...

  5. ajax application/json 的坑

    我们习惯使用application/json方式提交,所以会在ajax中指定contentType. $.ajax({ url: "http://localhost:3000", ...

  6. mac shell终端编辑命令行快捷键——行首行尾

    mac shell终端编辑命令行快捷键——行首行尾 ctrl+a //移到行首ctrl+e //移到行尾===========linux系统用============alt+a //移到光标所在单词首 ...

  7. struts2开发流程及配置,域对象对数据存储的3种方式

    一.开发流程 1)引入 jar 包,其中必须引入的有(我是用的struts是2.3.32) commons-fileupload-1.3.2.jar     |文件上传下载commons-io-2.2 ...

  8. C# 获得文件名

    string strFilePaht="文件路径"; Path.GetFileNameWithoutExtension(strFilePath);这个就是获取文件名的 还有的就是用 ...

  9. JMeter学习笔记(二)

    3.JMeter测试计划要素 JMeter中一个脚本即是一个测试计划,也是一个管理单元.JMeter的请求模拟与并发数(设置线程数,一个线程代表一个虚拟用户)设置都在脚本文件中一起设置. 要素一:脚本 ...

  10. Python中的strip()的理解

    在看到Python中strip的时候产生了疑问 strip() 用于移除字符串头尾指定的字符(默认为空格) 开始测试: >>> s = 'ncy_123.python' >&g ...