HttpClient使用学习
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使用学习的更多相关文章
- HttpClient研究学习总结
Http协议非常的重要,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人 ...
- Httpclient的学习(一)
1.名词解释 抓包: 抓包(packet capture)就是将网络传输发送与接收的数据包进行截获.重发.编辑.转存等操作,也用来检查网络安全.抓包也经常被用来进行数据截取等. Httpclient: ...
- HttpClient&&RestTemplate学习
1. 什么是HttpClient HttpClient是Apache下面的子项目,可以提供高效的,最新的,功能丰富的支持HTTP协议的客户端编程工具包. 2. 为什么要学习HttpClient Htt ...
- 【HttpClient】使用学习
HttpClient使用学习 HttpClient Tutorial:http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/in ...
- android通过HttpClient与服务器JSON交互
通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; i ...
- HttpClient客户端网络编程——高可用、高并发
本文是HttpClient的学习博客,RestTemplate是基于HttpClient的封装,feign可基于HttpClient进行网络通信. 那么作为较底层的客户端网络编程框架,该怎么配置使其能 ...
- 在ASP dot Net Core MVC中用Controllers调用你的Asp dotnet Core Web API 实现CRUD到远程数据库中,构建你的分布式应用(附Git地址)
本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...
- 在Core环境下用WebRequest连接上远程的web Api 实现数据的简单CRUD(附Git地址)
本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...
- System.Net.Http
System.Net.Http DotNet菜园 占个位置^-^ 2018-11-10 09:55:00修改 这个HttpClient的学习笔记一直迟迟未记录,只引用了其他博主的博客链接占个位置,但被 ...
随机推荐
- 深入理解Android的密度独立性
前言 安卓是一个只对硬件设备限制有很少限制的移动操作系统.生产商们几乎可以创造任何形状的.尺寸的和密度的屏幕的设备.设备可以有物理键盘和按钮或者只有虚 拟键盘和按钮.由于它的设备客制化的自由性给软件开 ...
- 推荐10款最常用的Android开发工具
我们使用各种语言进行开发时,总是会用到各种各样的开发工具.有些开发工具是开发人员的必备品,有些则是为了提高开发效率而用.Android开发同样也会用到多种开发工具,供开发人员设计.创建.测试和发布程序 ...
- 在eclipse中将android工程打包生成apk文件
1.)生成keystore 按照下面的命令行 在C:\Program Files\Java\jdk1.6.0_10\bin>目录下,输入keytool -genkey -alias androi ...
- Redis总结(二)C#中如何使用redis(转载)
上一篇讲述了安装redis<Redis总结(一)Redis安装>,同时也大致介绍了redis的优势和应用场景.本篇着重讲解.NET中如何使用redis和C#. Redis官网提供了很多开源 ...
- Spring boot 配置 swagger
1.maven配置包 <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dep ...
- 黑马程序猿——25,打印流,合并流,对象序列化,管道流,RandomAccessFile
------<ahref="http://www.itheima.com" target="blank">Java培训.Android培训.iOS培 ...
- SIFT 、Hog 、LBP 了解
SIFT.HOG.LBP,这三者都属于局部特征. 一.三者原理上的区别 1.SIFT:Scale-Invariant Feature Taransform,尺度不变特征变换. 尺度空间的极值检测:搜索 ...
- 将 数据从数据库 直接通过 pyspark 读入到dataframe
from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName("Python Spark S ...
- 停掉一台服务器,Nginx响应慢(转载)
测试发现的问题及解决办法 1.当后端两台IIS应用服务器都正常时,访问速度非常快,查看日志,原来一个请求,是后端两台服务器同时响应的; 2.为了模仿故障测试,停掉一台IIS应用服务器,这时再访问,请求 ...
- JSON传参
通过javascript将数据组织成json格式,然后传到java后台. 注意:前台json数组传参到后台时候需要将对象(json或json数组)转换成字符串(字符串数组). Simple: 1.前台 ...