概述
【注意】2014-02-28 HttpConnectionUtils 升级了!
1. 基于Apache HttpClient4
2. 添加获取图片的方法
3. 支持https
4. 支持会话保持
详见:NO.91 SSLPeerUnverifiedException 问题之解决(附HttpClientUtils升级版)
与三方交互一般采用HttpConnection或HttpClient(推荐,功能强大适应性强),且一定要设置连接超时时间及读取超时时间两个参数:
HttpConnection设置两参数例子:
HttpConnection httpConnection= new HttpConnection();
httpConnection.setConnectTimeout(50 * 1000); // 打开连接时间等待超时50秒
httpConnection.setReadTimeout(300 * 1000); // 等待读取返回数据超时300秒
HttpClient设置两个参数的例子:
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams managerParams = httpClient
.getHttpConnectionManager().getParams();
// 设置连接的超时时间
managerParams.setConnectionTimeout(50 * 1000);
// 设置读取数据的超时时间
managerParams.setSoTimeout(300 * 1000);
附自写工具采用HttpClient支持代理Proxy、支持用户名密码、支持域Domain模式
package amosryan.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
//import org.apache.log4j.Logger;
/**
* 建立Http连接的工具类
*
* @author liuzhen
* @since 2009-03-23
* @version V1.2 将原静态实现改为实例实现,以便参数设置
*/
public class HttpConnectionUtils {
// private static Logger logger =
// Logger.getLogger(HttpConnectionUtils.class);
/** 连接超时时间(默认3秒 3000ms) 单位毫秒(ms) */
private int connectionTimeout = 3000;
/** 读取数据超时时间(默认30秒 30000ms) 单位毫秒(ms) */
private int soTimeout = 30000;
/** 代理主机名 */
private String proxyHostName;
/** 代理端口 */
private int proxyPort;
/** 代理主机用户名 */
private String proxyUser;
/** 代理主机密码 */
private String proxyPwd;
/** 代理主机域 */
private String proxyDomain;
/** 字符集设置 */
private String charset = "UTF-8";
public String getProxyUser() {
return proxyUser;
}
public void setProxyUser(String proxyUser) {
this.proxyUser = proxyUser;
}
public String getProxyPwd() {
return proxyPwd;
}
public void setProxyPwd(String proxyPwd) {
this.proxyPwd = proxyPwd;
}
public String getProxyDomain() {
return proxyDomain;
}
public void setProxyDomain(String proxyDomain) {
this.proxyDomain = proxyDomain;
}
/**
* get方式连接
*
* @param url
* @param postData
* @return
* @throws Exception
*/
public String doGet(String url) throws Exception {
// 创建Get方法的实例
GetMethod getMethod = new GetMethod(url);
return doRequest(getMethod,null);
}
/**
* post方式连接
*
* @param url
* @param postData
* @return
* @throws Exception
*/
public String doPost(String url, String postData) throws Exception {
// 创建Post方法的实例
PostMethod postMethod = new PostMethod(url);
return doRequest(postMethod,postData);
}
private String doRequest(HttpMethodBase request, String postData) throws Exception {
// 创建HttpClient实例
HttpClient httpClient = new HttpClient();
// 设置连接的超时时间5s
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(connectionTimeout);
// 设置读取数据的超时时间8s
httpClient.getHttpConnectionManager().getParams()
.setSoTimeout(soTimeout);
// 设置代理
if (proxyHostName != null) {
httpClient.getHostConfiguration()
.setProxy(proxyHostName, proxyPort);
// 代理需要认证
if (proxyUser != null) {
UsernamePasswordCredentials upc = null;
if (proxyDomain != null) {// NTLM认证模式
upc = new NTCredentials(proxyUser, proxyPwd, proxyHostName,
proxyDomain);
} else {// BASIC模式
upc = new UsernamePasswordCredentials(proxyUser, proxyPwd);
}
httpClient.getState().setProxyCredentials(AuthScope.ANY, upc);
}
}
// 使用系统提供的默认的恢复策略
request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
if(postData!=null){
// 设置发送的内容
((PostMethod)request).setRequestBody(postData);
// 对发送的内容长度进行设定
if (postData.length() < Integer.MAX_VALUE) {
((PostMethod)request).setRequestContentLength(postData.length());
} else {
((PostMethod)request)
.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
}
}
// 指定请求内容的类型
request.setRequestHeader("Content-type", "text/xml; charset="
+ charset);
BufferedReader reader = null;
String backString = null;
try {
// 执行post方法
int statusCode = httpClient.executeMethod(request);
if (statusCode != HttpStatus.SC_OK) {// 如果连接正常,获得返回内容
throw new Exception("连接失败");
}
reader = new BufferedReader(new InputStreamReader(
request.getResponseBodyAsStream(), charset));
String line = null;
StringBuffer buffered = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffered.append(line);
}
backString = buffered.toString();
} catch (HttpException e) {// 发生致命的异常,可能是协议不对或者返回的内容有问题
// logger.info("Please check your provided http address!");
e.printStackTrace();
throw e;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {// 发生网络异常
e.printStackTrace();
throw e;
} finally {// 关闭输入输出流,释放连接
if (reader != null) {
reader.close();
}
request.releaseConnection();
}
return backString;
}
/**
* 获取连接超时时间 单位毫秒(ms)
*
* @return
*/
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public String getProxyHostName() {
return proxyHostName;
}
public void setProxyHostName(String proxyHostName) {
this.proxyHostName = proxyHostName;
}
public int getProxyPort() {
return proxyPort;
}
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public int getSoTimeout() {
return soTimeout;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
}
最后
以上就是爱笑裙子为你收集整理的NO.19 HttpConnection、HttpClient使用注意点(附http连接工具:采用HttpClient支持代理Proxy、支持用户名密码、支持域Domain模式) 的全部内容,希望文章能够帮你解决NO.19 HttpConnection、HttpClient使用注意点(附http连接工具:采用HttpClient支持代理Proxy、支持用户名密码、支持域Domain模式) 所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复