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. knockoutjs -- if 绑定

    参考:http://knockoutjs.com/documentation/if-binding.html If 绑定用来控制一部分html标签是否生成在DOM树中(html标签有data-bind ...

  2. 基于Ant Design UI框架的React项目

    概述 这款基于React开发的UI框架,界面非常简洁美观,在这篇文章中我主要为大家介绍一下如何用Ant开始搭建React项目 详细 代码下载:http://www.demodashi.com/demo ...

  3. 转载:【Linux+windows】PHP5.5安装PHPRedis扩展

    首先,你必须安装了 Redis服务器,然后才能安装php-redis扩展,就像先安装mysql,然后再将php-mysql扩展安装并引入(区别是:php-redis扩展插件php没有自带,php-my ...

  4. easyui框架Date日期类型以json形式显示到前台datagrid时,显示为[object Object]

    如下图,easyui当后台把时间数据返回转换成json然后加载在easyui的datagrid里面,显示为[object Object]      需要对时间格式添加格式的显示方法 /** * 时间格 ...

  5. Python-搭建Nginx+Django环境

    1.安装 flup 模块 下载:http://projects.unbit.it/downloads/uwsgi-latest.tar.gz 安装:python setup.py install 2. ...

  6. windows下LIB和DLL的区别与使用

    共有两种库: 一种是LIB包含了函数所在的DLL文件和文件中函数位置的信息(入口),代码由运行时加载在进程空间中的DLL提供,称为动态链接库dynamic link library. 一种是LIB包含 ...

  7. C++中四种类型转换以及const_cast是否能改变常量的问题

    we have four specific casting operators:dynamic_cast, reinterpret_cast, static_cast and const_cast. ...

  8. tp数据库操作

    1.常见的数据库操作//插入记录// $insert=Db::execute("insert into tp_user (username,password) values ('dome', ...

  9. Atitit.ide代码块折叠插件 eclipse

    Atitit.ide代码块折叠插件 eclipse 1. User Defined Regions  #region  ...  #endregion  插件com.cb.eclipse.foldin ...

  10. SMBUS的介绍与访问

    博文是为了总结自己在bios学习上面的点点滴滴,并且加深印象,由于本人水平有限,难免存在不足之处,望指正,同时感谢CSDN提供的平台.本文主要介绍的是SMBUS. 1  SMBUS的简介 特点: SM ...