HttpClient请求

  与三方交互一般采用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模式

[java] view plaincopyprint?
package unit;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.IOException;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;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.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.log4j.Logger;/** * 建立Http连接的工具类 *  *
@author AmosRyan *
@since 2009-03-23 *
@version V1.2 将原静态实现改为实例实现,以便参数设置 */
public class HttpConnectionUtils
{
private static Logger logger = Logger.getLogger(HttpConnectionUtils.class);
/** 连接超时时间(默认10秒 10000ms) 单位毫秒(ms) */
private int connectionTimeout = 10000;
/** 读取数据超时时间(默认30秒 30000ms) 单位毫秒(ms) */private int soTimeout = 30000;/** 代理主机名 */
private String proxyHostName;/** 代理主机名 */
private int proxyPort;
/** 代理主机用户名 */private String proxyUser;
/** 代理主机密码 */private String proxyPwd;/
** 代理主机域 */private String proxyDomain;
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;}p
ublic String getProxyDomain()
{return proxyDomain;}
public void setProxyDomain(String proxyDomain)
{this.proxyDomain = proxyDomain;}/
** * 获取连接超时时间 单位毫秒(ms) *  * @return */
public int getConnectionTimeout() {return connectionTimeout;}
/** * 设置连接超时时间(默认10秒 10000ms) 单位毫秒(ms) *  * @param 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;}
/** * 设置读取数据超时时间(默认30秒 30000ms) 单位毫秒(ms) *  * @param connectionTimeout */
public void setSoTimeout(int soTimeout) {this.soTimeout = soTimeout;}/** * post方式连接 *  * @param url * @param postData * @return * @throws Exception */public String doPost(String url, String postData) throws Exception {// 创建HttpClient实例HttpClient httpClient = new HttpClient();// 创建Post方法的实例PostMethod postMethod = new PostMethod(url);// 设置连接的超时时间httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);// 设置读取数据的超时时间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);}}// 使用系统提供的默认的恢复策略postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());// 设置发送的内容postMethod.setRequestBody(postData);// 对发送的内容长度进行设定if (postData.length() < Integer.MAX_VALUE) {postMethod.setRequestContentLength(postData.length());} else {postMethod.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);}// 指定请求内容的类型postMethod.setRequestHeader("Content-type", "text/xml; charset=GBK");DataInputStream input = null;ByteArrayOutputStream byteOut = new ByteArrayOutputStream();String dataString = null;try {// 执行post方法int statusCode = httpClient.executeMethod(postMethod);if (statusCode != HttpStatus.SC_OK) {// 如果连接正常,获得返回内容throw new Exception("连接失败");}input = new DataInputStream(postMethod.getResponseBodyAsStream());byte[] data = null;byte[] b = new byte[1024];int read = 0;while ((read = input.read(b)) > 0) {byteOut.write(b, 0, read);}byteOut.flush();data = byteOut.toByteArray();dataString = new String(data);} catch (HttpException e) {// 发生致命的异常,可能是协议不对或者返回的内容有问题logger.info("Please check your provided http address!");e.printStackTrace();throw e;} catch (IOException e) {// 发生网络异常e.printStackTrace();throw e;} finally {// 关闭输入输出流,释放连接if (input != null) {input.close();}byteOut.close();postMethod.releaseConnection();}return dataString;}} 

你可能感兴趣的:(httpclient)