﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-少年阿宾-随笔分类-httpClient</title><link>http://www.blogjava.net/stevenjohn/category/51822.html</link><description>那些青春的岁月</description><language>zh-cn</language><lastBuildDate>Fri, 20 Jan 2017 00:23:26 GMT</lastBuildDate><pubDate>Fri, 20 Jan 2017 00:23:26 GMT</pubDate><ttl>60</ttl><item><title>httpClient Https 单向不验证(httpClient连接池) </title><link>http://www.blogjava.net/stevenjohn/archive/2016/04/27/430267.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 27 Apr 2016 11:04:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2016/04/27/430267.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/430267.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2016/04/27/430267.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/430267.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/430267.html</trackback:ping><description><![CDATA[<div>废话少说，直接上代码，以前都是调用别人写好的，现在有时间自己弄下，具体功能如下：<br />1、httpClient+http+线程池：<br />2、httpClient+https(单向不验证证书)+线程池：<br /><br />https在%TOMCAT_HOME%/conf/server.xml里面的配置文件<br /><div>&lt;Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"&nbsp;</div><div>&nbsp; &nbsp; &nbsp;maxThreads="150" scheme="https" secure="true"&nbsp;</div><div>&nbsp; &nbsp; &nbsp;clientAuth="false" keystoreFile="D:/tomcat.keystore"&nbsp;</div><div>&nbsp; &nbsp; &nbsp;keystorePass="heikaim" sslProtocol="TLS" &nbsp;executor="tomcatThreadPool"/&gt;&nbsp;</div>其中&nbsp;clientAuth="false"表示不开启证书验证，只是单存的走https<br /><br /><br /><br /><pre style="background-color: #ffffff; font-family: 宋体; font-size: 9pt;"><span style="color:#000080;font-weight:bold;">package </span>com.abin.lee.util;<br /><br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.commons.collections4.MapUtils;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.commons.lang3.StringUtils;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.*;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.HttpRequestRetryHandler;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.config.CookieSpecs;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.config.RequestConfig;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.entity.UrlEncodedFormEntity;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.methods.CloseableHttpResponse;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.methods.HttpGet;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.methods.HttpPost;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.client.protocol.HttpClientContext;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.config.Registry;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.config.RegistryBuilder;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.conn.ConnectTimeoutException;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.conn.socket.ConnectionSocketFactory;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.conn.socket.PlainConnectionSocketFactory;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.conn.ssl.NoopHostnameVerifier;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.conn.ssl.SSLConnectionSocketFactory;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.entity.StringEntity;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.impl.client.CloseableHttpClient;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.impl.client.HttpClients;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.impl.conn.PoolingHttpClientConnectionManager;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.message.BasicHeader;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.message.BasicNameValuePair;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.protocol.HttpContext;<br /><span style="color:#000080;font-weight:bold;">import </span>org.apache.http.util.EntityUtils;<br /><br /><span style="color:#000080;font-weight:bold;">import </span>javax.net.ssl.*;<br /><span style="color:#000080;font-weight:bold;">import </span>java.io.IOException;<br /><span style="color:#000080;font-weight:bold;">import </span>java.io.InterruptedIOException;<br /><span style="color:#000080;font-weight:bold;">import </span>java.net.UnknownHostException;<br /><span style="color:#000080;font-weight:bold;">import </span>java.nio.charset.Charset;<br /><span style="color:#000080;font-weight:bold;">import </span>java.security.cert.CertificateException;<br /><span style="color:#000080;font-weight:bold;">import </span>java.security.cert.X509Certificate;<br /><span style="color:#000080;font-weight:bold;">import </span>java.util.*;<br /><br /><span style="color:#808080;font-style:italic;">/**<br /></span><span style="color:#808080;font-style:italic;"> * Created with IntelliJ IDEA.<br /></span><span style="color:#808080;font-style:italic;"> * User: abin<br /></span><span style="color:#808080;font-style:italic;"> * Date: 16-4-18<br /></span><span style="color:#808080;font-style:italic;"> * Time: 上午10:24<br /></span><span style="color:#808080;font-style:italic;"> * To change this template use File | Settings | File Templates.<br /></span><span style="color:#808080;font-style:italic;"> */<br /></span><span style="color:#000080;font-weight:bold;">public class </span>HttpClientUtil {<br />    <span style="color:#000080;font-weight:bold;">private static </span>CloseableHttpClient <span style="color:#660e7a;font-style:italic;">httpsClient </span>= <span style="color:#000080;font-weight:bold;">null</span>;<br />    <span style="color:#000080;font-weight:bold;">private static </span>CloseableHttpClient <span style="color:#660e7a;font-style:italic;">httpClient </span>= <span style="color:#000080;font-weight:bold;">null</span>;<br /><br />    <span style="color:#000080;font-weight:bold;">static </span>{<br />        <span style="color:#660e7a;font-style:italic;">httpClient </span>= <span style="font-style:italic;">getHttpClient</span>();<br />        <span style="color:#660e7a;font-style:italic;">httpsClient </span>= <span style="font-style:italic;">getHttpsClient</span>();<br />    }<br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>CloseableHttpClient getHttpClient() {<br />        <span style="color:#000080;font-weight:bold;">try </span>{<br />            <span style="color:#660e7a;font-style:italic;">httpClient </span>= HttpClients.<span style="font-style:italic;">custom</span>()<br />                    .setConnectionManager(PoolManager.<span style="font-style:italic;">getHttpPoolInstance</span>())<br />                    .setConnectionManagerShared(<span style="color:#000080;font-weight:bold;">true</span>)<br />                    .setDefaultRequestConfig(<span style="font-style:italic;">requestConfig</span>())<br />                    .setRetryHandler(<span style="font-style:italic;">retryHandler</span>())<br />                    .build();<br />        } <span style="color:#000080;font-weight:bold;">catch </span>(Exception e) {<br />            e.printStackTrace();<br />        }<br />        <span style="color:#000080;font-weight:bold;">return </span><span style="color:#660e7a;font-style:italic;">httpClient</span>;<br />    }<br /><br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>CloseableHttpClient getHttpsClient() {<br />        <span style="color:#000080;font-weight:bold;">try </span>{<br />            <span style="color:#808080;font-style:italic;">//Secure Protocol implementation.<br /></span> SSLContext ctx = SSLContext.<span style="font-style:italic;">getInstance</span>(<span style="color:#008000;font-weight:bold;">"SSL"</span>);<br />            <span style="color:#808080;font-style:italic;">//Implementation of a trust manager for X509 certificates<br /></span> TrustManager x509TrustManager = <span style="color:#000080;font-weight:bold;">new </span>X509TrustManager() {<br />                <span style="color:#000080;font-weight:bold;">public void </span>checkClientTrusted(X509Certificate[] xcs,<br />                                               String string) <span style="color:#000080;font-weight:bold;">throws </span>CertificateException {<br />                }<br />                <span style="color:#000080;font-weight:bold;">public void </span>checkServerTrusted(X509Certificate[] xcs,<br />                                               String string) <span style="color:#000080;font-weight:bold;">throws </span>CertificateException {<br />                }<br />                <span style="color:#000080;font-weight:bold;">public </span>X509Certificate[] getAcceptedIssuers() {<br />                    <span style="color:#000080;font-weight:bold;">return null</span>;<br />                }<br />            };<br />            ctx.init(<span style="color:#000080;font-weight:bold;">null</span>, <span style="color:#000080;font-weight:bold;">new </span>TrustManager[]{x509TrustManager}, <span style="color:#000080;font-weight:bold;">null</span>);<br />            <span style="color:#808080;font-style:italic;">//首先设置全局的标准cookie策略<br /></span><span style="color:#808080;font-style:italic;">//            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();<br /></span> ConnectionSocketFactory connectionSocketFactory = <span style="color:#000080;font-weight:bold;">new </span>SSLConnectionSocketFactory(ctx, <span style="color:#660e7a;font-style:italic;">hostnameVerifier</span>);<br />            Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry = RegistryBuilder.&lt;ConnectionSocketFactory&gt;<span style="font-style:italic;">create</span>()<br />                    .register(<span style="color:#008000;font-weight:bold;">"http"</span>, PlainConnectionSocketFactory.<span style="color:#660e7a;font-weight:bold;font-style:italic;">INSTANCE</span>)<br />                    .register(<span style="color:#008000;font-weight:bold;">"https"</span>, connectionSocketFactory).build();<br />            <span style="color:#808080;font-style:italic;">// 设置连接池<br /></span> <span style="color:#660e7a;font-style:italic;">httpsClient </span>= HttpClients.<span style="font-style:italic;">custom</span>()<br />                    .setConnectionManager(PoolsManager.<span style="font-style:italic;">getHttpsPoolInstance</span>(socketFactoryRegistry))<br />                    .setConnectionManagerShared(<span style="color:#000080;font-weight:bold;">true</span>)<br />                    .setDefaultRequestConfig(<span style="font-style:italic;">requestConfig</span>())<br />                    .setRetryHandler(<span style="font-style:italic;">retryHandler</span>())<br />                    .build();<br />        } <span style="color:#000080;font-weight:bold;">catch </span>(Exception e) {<br />            e.printStackTrace();<br />        }<br />        <span style="color:#000080;font-weight:bold;">return </span><span style="color:#660e7a;font-style:italic;">httpsClient</span>;<br />    }<br /><br />    <span style="color:#808080;font-style:italic;">// 配置请求的超时设置<br /></span><span style="color:#808080;font-style:italic;">    //首先设置全局的标准cookie策略<br /></span> <span style="color:#000080;font-weight:bold;">public static </span>RequestConfig requestConfig(){<br />        RequestConfig requestConfig = RequestConfig.<span style="font-style:italic;">custom</span>()<br />                .setCookieSpec(CookieSpecs.<span style="color:#660e7a;font-weight:bold;font-style:italic;">STANDARD_STRICT</span>)<br />                .setConnectionRequestTimeout(<span style="color:#0000ff;">20000</span>)<br />                .setConnectTimeout(<span style="color:#0000ff;">20000</span>)<br />                .setSocketTimeout(<span style="color:#0000ff;">20000</span>)<br />                .build();<br />        <span style="color:#000080;font-weight:bold;">return </span>requestConfig;<br />    }<br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>HttpRequestRetryHandler retryHandler(){<br />        <span style="color:#808080;font-style:italic;">//请求重试处理<br /></span> HttpRequestRetryHandler httpRequestRetryHandler = <span style="color:#000080;font-weight:bold;">new </span>HttpRequestRetryHandler() {<br />            <span style="color:#000080;font-weight:bold;">public boolean </span>retryRequest(IOException exception,<span style="color:#000080;font-weight:bold;">int </span>executionCount, HttpContext context) {<br />                <span style="color:#000080;font-weight:bold;">if </span>(executionCount &gt;= <span style="color:#0000ff;">5</span>) {<span style="color:#808080;font-style:italic;">// 如果已经重试了5次，就放弃<br /></span> <span style="color:#000080;font-weight:bold;">return false</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">if </span>(exception <span style="color:#000080;font-weight:bold;">instanceof </span>NoHttpResponseException) {<span style="color:#808080;font-style:italic;">// 如果服务器丢掉了连接，那么就重试<br /></span> <span style="color:#000080;font-weight:bold;">return true</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">if </span>(exception <span style="color:#000080;font-weight:bold;">instanceof </span>SSLHandshakeException) {<span style="color:#808080;font-style:italic;">// 不要重试SSL握手异常<br /></span> <span style="color:#000080;font-weight:bold;">return false</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">if </span>(exception <span style="color:#000080;font-weight:bold;">instanceof </span>InterruptedIOException) {<span style="color:#808080;font-style:italic;">// 超时<br /></span> <span style="color:#000080;font-weight:bold;">return false</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">if </span>(exception <span style="color:#000080;font-weight:bold;">instanceof </span>UnknownHostException) {<span style="color:#808080;font-style:italic;">// 目标服务器不可达<br /></span> <span style="color:#000080;font-weight:bold;">return false</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">if </span>(exception <span style="color:#000080;font-weight:bold;">instanceof </span>ConnectTimeoutException) {<span style="color:#808080;font-style:italic;">// 连接被拒绝<br /></span> <span style="color:#000080;font-weight:bold;">return false</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">if </span>(exception <span style="color:#000080;font-weight:bold;">instanceof </span>SSLException) {<span style="color:#808080;font-style:italic;">// ssl握手异常<br /></span> <span style="color:#000080;font-weight:bold;">return false</span>;<br />                }<br /><br />                HttpClientContext clientContext = HttpClientContext.<span style="font-style:italic;">adapt</span>(context);<br />                HttpRequest request = clientContext.getRequest();<br />                <span style="color:#808080;font-style:italic;">// 如果请求是幂等的，就再次尝试<br /></span> <span style="color:#000080;font-weight:bold;">if </span>(!(request <span style="color:#000080;font-weight:bold;">instanceof </span>HttpEntityEnclosingRequest)) {<br />                    <span style="color:#000080;font-weight:bold;">return true</span>;<br />                }<br />                <span style="color:#000080;font-weight:bold;">return false</span>;<br />            }<br />        };<br />        <span style="color:#000080;font-weight:bold;">return </span>httpRequestRetryHandler;<br />    }<br /><br /><br /><br />    <span style="color:#808080;font-style:italic;">//创建HostnameVerifier<br /></span><span style="color:#808080;font-style:italic;">    //用于解决javax.net.ssl.SSLException: hostname in certificate didn't match: &lt;123.125.97.66&gt; != &lt;123.125.97.241&gt;<br /></span> <span style="color:#000080;font-weight:bold;">static </span>HostnameVerifier <span style="color:#660e7a;font-style:italic;">hostnameVerifier </span>= <span style="color:#000080;font-weight:bold;">new </span>NoopHostnameVerifier(){<br />        <span style="color:#808000;">@Override<br /></span> <span style="color:#000080;font-weight:bold;">public boolean </span>verify(String s, SSLSession sslSession) {<br />            <span style="color:#000080;font-weight:bold;">return super</span>.verify(s, sslSession);<br />        }<br />    };<br /><br /><br />    <span style="color:#000080;font-weight:bold;">public static class </span>PoolManager {<br />        <span style="color:#000080;font-weight:bold;">public static </span>PoolingHttpClientConnectionManager <span style="color:#660e7a;font-style:italic;">clientConnectionManager </span>= <span style="color:#000080;font-weight:bold;">null</span>;<br />        <span style="color:#000080;font-weight:bold;">private static int </span><span style="color:#660e7a;font-style:italic;">maxTotal </span>= <span style="color:#0000ff;">200</span>;<br />        <span style="color:#000080;font-weight:bold;">private static int </span><span style="color:#660e7a;font-style:italic;">defaultMaxPerRoute </span>= <span style="color:#0000ff;">100</span>;<br /><br />        <span style="color:#000080;font-weight:bold;">private </span>PoolManager(){<br />            <span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>.setMaxTotal(<span style="color:#660e7a;font-style:italic;">maxTotal</span>);<br />            <span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>.setDefaultMaxPerRoute(<span style="color:#660e7a;font-style:italic;">defaultMaxPerRoute</span>);<br />        }<br /><br />        <span style="color:#000080;font-weight:bold;">private static class </span>PoolManagerHolder{<br />            <span style="color:#000080;font-weight:bold;">public static  </span>PoolManager <span style="color:#660e7a;font-style:italic;">instance </span>= <span style="color:#000080;font-weight:bold;">new </span>PoolManager();<br />        }<br /><br />        <span style="color:#000080;font-weight:bold;">public static </span>PoolManager getInstance() {<br />            <span style="color:#000080;font-weight:bold;">if</span>(<span style="color:#000080;font-weight:bold;">null </span>== <span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>)<br />                <span style="color:#660e7a;font-style:italic;">clientConnectionManager </span>= <span style="color:#000080;font-weight:bold;">new </span>PoolingHttpClientConnectionManager();<br />            <span style="color:#000080;font-weight:bold;">return </span>PoolManagerHolder.<span style="color:#660e7a;font-style:italic;">instance</span>;<br />        }<br /><br />        <span style="color:#000080;font-weight:bold;">public static </span>PoolingHttpClientConnectionManager getHttpPoolInstance() {<br />            PoolManager.<span style="font-style:italic;">getInstance</span>();<br /><span style="color:#808080;font-style:italic;">//            System.out.println("getAvailable=" + clientConnectionManager.getTotalStats().getAvailable());<br /></span><span style="color:#808080;font-style:italic;">//            System.out.println("getLeased=" + clientConnectionManager.getTotalStats().getLeased());<br /></span><span style="color:#808080;font-style:italic;">//            System.out.println("getMax=" + clientConnectionManager.getTotalStats().getMax());<br /></span><span style="color:#808080;font-style:italic;">//            System.out.println("getPending="+clientConnectionManager.getTotalStats().getPending());<br /></span> <span style="color:#000080;font-weight:bold;">return </span>PoolManager.<span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>;<br />        }<br /><br /><br />    }<br /><br />    <span style="color:#000080;font-weight:bold;">public static class </span>PoolsManager {<br />        <span style="color:#000080;font-weight:bold;">public static </span>PoolingHttpClientConnectionManager <span style="color:#660e7a;font-style:italic;">clientConnectionManager </span>= <span style="color:#000080;font-weight:bold;">null</span>;<br />        <span style="color:#000080;font-weight:bold;">private static int </span><span style="color:#660e7a;font-style:italic;">maxTotal </span>= <span style="color:#0000ff;">200</span>;<br />        <span style="color:#000080;font-weight:bold;">private static int </span><span style="color:#660e7a;font-style:italic;">defaultMaxPerRoute </span>= <span style="color:#0000ff;">100</span>;<br /><br />        <span style="color:#000080;font-weight:bold;">private </span>PoolsManager(){<br />            <span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>.setMaxTotal(<span style="color:#660e7a;font-style:italic;">maxTotal</span>);<br />            <span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>.setDefaultMaxPerRoute(<span style="color:#660e7a;font-style:italic;">defaultMaxPerRoute</span>);<br />        }<br /><br />        <span style="color:#000080;font-weight:bold;">private static class </span>PoolsManagerHolder{<br />            <span style="color:#000080;font-weight:bold;">public static  </span>PoolsManager <span style="color:#660e7a;font-style:italic;">instance </span>= <span style="color:#000080;font-weight:bold;">new </span>PoolsManager();<br />        }<br /><br />        <span style="color:#000080;font-weight:bold;">public static </span>PoolsManager getInstance(Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry) {<br />            <span style="color:#000080;font-weight:bold;">if</span>(<span style="color:#000080;font-weight:bold;">null </span>== <span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>)<br />                <span style="color:#660e7a;font-style:italic;">clientConnectionManager </span>= <span style="color:#000080;font-weight:bold;">new </span>PoolingHttpClientConnectionManager(socketFactoryRegistry);<br />            <span style="color:#000080;font-weight:bold;">return </span>PoolsManagerHolder.<span style="color:#660e7a;font-style:italic;">instance</span>;<br />        }<br /><br />        <span style="color:#000080;font-weight:bold;">public static </span>PoolingHttpClientConnectionManager getHttpsPoolInstance(Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry) {<br />            PoolsManager.<span style="font-style:italic;">getInstance</span>(socketFactoryRegistry);<br /><span style="color:#808080;font-style:italic;">//            System.out.println("getAvailable=" + clientConnectionManager.getTotalStats().getAvailable());<br /></span><span style="color:#808080;font-style:italic;">//            System.out.println("getLeased=" + clientConnectionManager.getTotalStats().getLeased());<br /></span><span style="color:#808080;font-style:italic;">//            System.out.println("getMax=" + clientConnectionManager.getTotalStats().getMax());<br /></span><span style="color:#808080;font-style:italic;">//            System.out.println("getPending="+clientConnectionManager.getTotalStats().getPending());<br /></span> <span style="color:#000080;font-weight:bold;">return </span>PoolsManager.<span style="color:#660e7a;font-style:italic;">clientConnectionManager</span>;<br />        }<br /><br />    }<br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>String httpPost(Map&lt;String, String&gt; request, String httpUrl){<br />        String result = <span style="color:#008000;font-weight:bold;">""</span>;<br />        CloseableHttpClient httpClient = <span style="font-style:italic;">getHttpClient</span>();<br />        <span style="color:#000080;font-weight:bold;">try </span>{<br />            <span style="color:#000080;font-weight:bold;">if</span>(MapUtils.<span style="font-style:italic;">isEmpty</span>(request))<br />                <span style="color:#000080;font-weight:bold;">throw new </span>Exception(<span style="color:#008000;font-weight:bold;">"请求参数不能为空"</span>);<br />            HttpPost httpPost = <span style="color:#000080;font-weight:bold;">new </span>HttpPost(httpUrl);<br />            List&lt;NameValuePair&gt; nvps = <span style="color:#000080;font-weight:bold;">new </span>ArrayList&lt;NameValuePair&gt;();<br />            <span style="color:#000080;font-weight:bold;">for</span>(Iterator&lt;Map.Entry&lt;String, String&gt;&gt; iterator=request.entrySet().iterator(); iterator.hasNext();){<br />                Map.Entry&lt;String, String&gt; entry = iterator.next();<br />                nvps.add(<span style="color:#000080;font-weight:bold;">new </span>BasicNameValuePair(entry.getKey(), entry.getValue()));<br />            }<br />            httpPost.setEntity(<span style="color:#000080;font-weight:bold;">new </span>UrlEncodedFormEntity(nvps, Consts.<span style="color:#660e7a;font-weight:bold;font-style:italic;">UTF_8</span>));<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing request: " </span>+ httpPost.getRequestLine());<br />            CloseableHttpResponse response = httpClient.execute(httpPost);<br />            result = EntityUtils.<span style="font-style:italic;">toString</span>(response.getEntity());<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing response: "</span>+ result);<br />        } <span style="color:#000080;font-weight:bold;">catch </span>(Exception e) {<br />            <span style="color:#000080;font-weight:bold;">throw new </span>RuntimeException(e);<br />        } <span style="color:#000080;font-weight:bold;">finally </span>{<br />            <span style="color:#000080;font-weight:bold;">try </span>{<br />                httpClient.close();<br />            } <span style="color:#000080;font-weight:bold;">catch </span>(IOException e) {<br />                e.printStackTrace();<br />            }<br />        }<br />        <span style="color:#000080;font-weight:bold;">return </span>result;<br />    }<br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>String httpPost(String json, String httpUrl, Map&lt;String, String&gt; headers){<br />        String result = <span style="color:#008000;font-weight:bold;">""</span>;<br />        CloseableHttpClient httpClient = <span style="font-style:italic;">getHttpClient</span>();<br />        <span style="color:#000080;font-weight:bold;">try </span>{<br />            <span style="color:#000080;font-weight:bold;">if</span>(StringUtils.<span style="font-style:italic;">isBlank</span>(json))<br />                <span style="color:#000080;font-weight:bold;">throw new </span>Exception(<span style="color:#008000;font-weight:bold;">"请求参数不能为空"</span>);<br />            HttpPost httpPost = <span style="color:#000080;font-weight:bold;">new </span>HttpPost(httpUrl);<br />            <span style="color:#000080;font-weight:bold;">for</span>(Iterator&lt;Map.Entry&lt;String, String&gt;&gt; iterator=headers.entrySet().iterator();iterator.hasNext();){<br />                Map.Entry&lt;String, String&gt; entry = iterator.next();<br />                Header header = <span style="color:#000080;font-weight:bold;">new </span>BasicHeader(entry.getKey(), entry.getValue());<br />                httpPost.setHeader(header);<br />            }<br />            httpPost.setEntity(<span style="color:#000080;font-weight:bold;">new </span>StringEntity(json, Charset.<span style="font-style:italic;">forName</span>(<span style="color:#008000;font-weight:bold;">"UTF-8"</span>)));<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing request: " </span>+ httpPost.getRequestLine());<br />            CloseableHttpResponse response = httpClient.execute(httpPost);<br />            result = EntityUtils.<span style="font-style:italic;">toString</span>(response.getEntity());<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing response: "</span>+ result);<br />        } <span style="color:#000080;font-weight:bold;">catch </span>(Exception e) {<br />            <span style="color:#000080;font-weight:bold;">throw new </span>RuntimeException(e);<br />        } <span style="color:#000080;font-weight:bold;">finally </span>{<br />            <span style="color:#000080;font-weight:bold;">try </span>{<br />                httpClient.close();<br />            } <span style="color:#000080;font-weight:bold;">catch </span>(IOException e) {<br />                e.printStackTrace();<br />            }<br />        }<br />        <span style="color:#000080;font-weight:bold;">return </span>result;<br />    }<br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>String httpGet(String httpUrl, Map&lt;String, String&gt; headers) {<br />        String result = <span style="color:#008000;font-weight:bold;">""</span>;<br />        CloseableHttpClient httpClient = <span style="font-style:italic;">getHttpClient</span>();<br />        <span style="color:#000080;font-weight:bold;">try </span>{<br />            HttpGet httpGet = <span style="color:#000080;font-weight:bold;">new </span>HttpGet(httpUrl);<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing request: " </span>+ httpGet.getRequestLine());<br />            <span style="color:#000080;font-weight:bold;">for</span>(Iterator&lt;Map.Entry&lt;String, String&gt;&gt; iterator=headers.entrySet().iterator();iterator.hasNext();){<br />                Map.Entry&lt;String, String&gt; entry = iterator.next();<br />                Header header = <span style="color:#000080;font-weight:bold;">new </span>BasicHeader(entry.getKey(), entry.getValue());<br />                httpGet.setHeader(header);<br />            }<br />            CloseableHttpResponse response = httpClient.execute(httpGet);<br />            result = EntityUtils.<span style="font-style:italic;">toString</span>(response.getEntity());<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing response: "</span>+ result);<br />        } <span style="color:#000080;font-weight:bold;">catch </span>(Exception e) {<br />            <span style="color:#000080;font-weight:bold;">throw new </span>RuntimeException(e);<br />        } <span style="color:#000080;font-weight:bold;">finally </span>{<br />            <span style="color:#000080;font-weight:bold;">try </span>{<br />                httpClient.close();<br />            } <span style="color:#000080;font-weight:bold;">catch </span>(IOException e) {<br />                e.printStackTrace();<br />            }<br />        }<br />        <span style="color:#000080;font-weight:bold;">return </span>result;<br />    }<br /><br /><br />    <span style="color:#000080;font-weight:bold;">public static </span>String httpGet(String httpUrl) {<br />        String result = <span style="color:#008000;font-weight:bold;">""</span>;<br />        CloseableHttpClient httpClient = <span style="font-style:italic;">getHttpClient</span>();<br />        <span style="color:#000080;font-weight:bold;">try </span>{<br />            HttpGet httpGet = <span style="color:#000080;font-weight:bold;">new </span>HttpGet(httpUrl);<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing request: " </span>+ httpGet.getRequestLine());<br />            CloseableHttpResponse response = httpClient.execute(httpGet);<br />            result = EntityUtils.<span style="font-style:italic;">toString</span>(response.getEntity());<br />            System.<span style="color:#660e7a;font-weight:bold;font-style:italic;">out</span>.println(<span style="color:#008000;font-weight:bold;">"Executing response: "</span>+ result);<br />        } <span style="color:#000080;font-weight:bold;">catch </span>(Exception e) {<br />            <span style="color:#000080;font-weight:bold;">throw new </span>RuntimeException(e);<br />        } <span style="color:#000080;font-weight:bold;">finally </span>{<br />            <span style="color:#000080;font-weight:bold;">try </span>{<br />                httpClient.close();<br />            } <span style="color:#000080;font-weight:bold;">catch </span>(IOException e) {<br />                e.printStackTrace();<br />            }<br />        }<br />        <span style="color:#000080;font-weight:bold;">return </span>result;<br />    }<br /><br /><br />  </pre></div><div><br /><br /><br />maven依赖：<br /><div>&nbsp; &lt;!--httpclient--&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &lt;dependency&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;artifactId&gt;httpclient&lt;/artifactId&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;version&gt;4.5.2&lt;/version&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/dependency&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &lt;dependency&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;artifactId&gt;httpcore&lt;/artifactId&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;version&gt;4.4.4&lt;/version&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/dependency&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &lt;dependency&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;artifactId&gt;httpmime&lt;/artifactId&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;version&gt;4.5.2&lt;/version&gt;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/dependency&gt;<br /><br /><pre style="background-color: #ffffff; font-family: 宋体; font-size: 9pt;"><span style="background-color:#efefef;">&lt;</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">dependency</span><span style="background-color:#efefef;">&gt;</span><br />    <span style="background-color:#efefef;">&lt;</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">groupId</span><span style="background-color:#efefef;">&gt;</span>org.apache.commons<span style="background-color:#efefef;">&lt;/</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">groupId</span><span style="background-color:#efefef;">&gt;</span><br />    <span style="background-color:#efefef;">&lt;</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">artifactId</span><span style="background-color:#efefef;">&gt;</span>commons-collections4<span style="background-color:#efefef;">&lt;/</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">artifactId</span><span style="background-color:#efefef;">&gt;</span><br />    <span style="background-color:#efefef;">&lt;</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">version</span><span style="background-color:#efefef;">&gt;</span>4.1<span style="background-color:#efefef;">&lt;/</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">version</span><span style="background-color:#efefef;">&gt;</span><br /><span style="background-color:#efefef;">&lt;/</span><span style="color:#000080;background-color:#efefef;font-weight:bold;">dependency</span><span style="background-color:#efefef;">&gt;</span><br /></pre></div></div><img src ="http://www.blogjava.net/stevenjohn/aggbug/430267.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2016-04-27 19:04 <a href="http://www.blogjava.net/stevenjohn/archive/2016/04/27/430267.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpAsyncClient  官方实例一</title><link>http://www.blogjava.net/stevenjohn/archive/2013/04/28/398553.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Sun, 28 Apr 2013 08:26:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/04/28/398553.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/398553.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/04/28/398553.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/398553.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/398553.html</trackback:ping><description><![CDATA[实例一：<br />
<p>package com.abin.lee.async;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;<br />import org.apache.http.nio.client.HttpAsyncClient;<br />import org.apache.http.nio.reactor.IOReactorException;<br />import org.junit.Test;</p>
<p>import java.io.IOException;<br />import java.util.concurrent.Future;</p>
<p>/**<br />&nbsp;* Created with IntelliJ IDEA.<br />&nbsp;* User: abin<br />&nbsp;* Date: 13-4-23<br />&nbsp;* Time: 下午6:13<br />&nbsp;* To change this template use File | Settings | File Templates.<br />&nbsp;*/<br />public class HttpAsyncClientTest {<br />&nbsp;&nbsp;&nbsp; private static final String HttpUrl="<a href="http://localhost:8100/MyThread/HttpClientPostProxyServlet">http://localhost:8100/MyThread/HttpClientPostProxyServlet</a>";<br />&nbsp;&nbsp;&nbsp; @Test<br />&nbsp;&nbsp;&nbsp; public void testHttpAsyncClient() throws IOException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpAsyncClient httpAsyncClient=new DefaultHttpAsyncClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpAsyncClient.start();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpPost request=null;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request=new HttpPost(HttpUrl);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Future&lt;HttpResponse&gt; future=httpAsyncClient.execute(request,null);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse response=future.get();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("response="+response);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }catch(Exception e){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(!request.isAborted()){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request.abort();;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpAsyncClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; }<br />}<br /></p><br /><br /><br /><br /><br /><br /><br />实例二：<br />
<p>package com.abin.lee.async;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.concurrent.FutureCallback;<br />import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;<br />import org.apache.http.nio.client.HttpAsyncClient;<br />import org.junit.Test;</p>
<p>import java.io.IOException;<br />import java.util.concurrent.CountDownLatch;<br />import java.util.concurrent.Future;</p>
<p>/**<br />&nbsp;* Created with IntelliJ IDEA.<br />&nbsp;* User: abin<br />&nbsp;* Date: 13-4-23<br />&nbsp;* Time: 下午6:13<br />&nbsp;* To change this template use File | Settings | File Templates.<br />&nbsp;*/<br />public class HttpAsyncClientFutureCallBackTest {<br />&nbsp;&nbsp;&nbsp; private static final String HttpUrl="<a href="http://localhost:8100/MyThread/HttpClientGetProxyServlet">http://localhost:8100/MyThread/HttpClientGetProxyServlet</a>";<br />&nbsp;&nbsp;&nbsp; private static final String HttpOneUrl="<a href="http://localhost:8100/MyThread/HttpClientGetOneServlet">http://localhost:8100/MyThread/HttpClientGetOneServlet</a>";<br />&nbsp;&nbsp;&nbsp; private static final String HttpTwoUrl="<a href="http://localhost:8100/MyThread/HttpClientGetTwoServlet">http://localhost:8100/MyThread/HttpClientGetTwoServlet</a>";<br />&nbsp;&nbsp;&nbsp; @Test<br />&nbsp;&nbsp;&nbsp; public void testHttpAsyncClientFutureCallBack() throws IOException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpAsyncClient httpAsyncClient=new DefaultHttpAsyncClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpAsyncClient.start();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet[] requests=null;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; requests=new HttpGet[]{new HttpGet(HttpUrl),new HttpGet(HttpOneUrl),new HttpGet(HttpTwoUrl)};<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final CountDownLatch latch=new CountDownLatch(requests.length);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for(final HttpGet request:requests){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpAsyncClient.execute(request,new FutureCallback&lt;HttpResponse&gt;() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Override<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void completed(HttpResponse httpResponse) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine()+"---&gt;"+httpResponse.getStatusLine());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //To change body of implemented methods use File | Settings | File Templates.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Override<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void failed(Exception e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine()+"--&gt;"+e.getMessage());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //To change body of implemented methods use File | Settings | File Templates.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Override<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void cancelled() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine()+"---&gt;"+" cancelled");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //To change body of implemented methods use File | Settings | File Templates.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }) ;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.await();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("shutting down");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }catch(Exception e){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpAsyncClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; }<br />}<br /></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/398553.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-04-28 16:26 <a href="http://www.blogjava.net/stevenjohn/archive/2013/04/28/398553.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient HttpDelete</title><link>http://www.blogjava.net/stevenjohn/archive/2013/04/20/398117.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Fri, 19 Apr 2013 16:54:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/04/20/398117.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/398117.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/04/20/398117.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/398117.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/398117.html</trackback:ping><description><![CDATA[<div>&nbsp; /**&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* HTTP DELETE方法进行删除操作&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @param url&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @param map&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @return&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @throws ClientProtocolException&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @throws IOException&nbsp;</div><div>&nbsp; &nbsp; &nbsp;*/ &nbsp;</div><div>&nbsp; &nbsp; public static String remoteDelete(String url, Map&lt;String, String&gt; map) throws ClientProtocolException, IOException{ &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; url = JETSUM_PLATFORM_SERVER+url; &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; HttpClient httpclient = new DefaultHttpClient(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; HttpDelete httpdelete= new HttpDelete(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; List&lt;NameValuePair&gt; formparams = setHttpParams(map); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; String param = URLEncodedUtils.format(formparams, "UTF-8"); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; httpdelete.setURI(URI.create(url + "?" + param)); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; HttpResponse response = httpclient.execute(httpdelete); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; String httpEntityContent = GetHttpEntityContent(response); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; httpdelete.abort(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; return httpEntityContent; &nbsp; &nbsp;&nbsp;</div>&nbsp; &nbsp; } &nbsp; &nbsp; &nbsp;&nbsp;<br /><br /><br /><br /><br /><div>&nbsp; &nbsp;/**&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* 设置请求参数&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @param map&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @return&nbsp;</div><div>&nbsp; &nbsp; &nbsp;*/ &nbsp;</div><div>&nbsp; &nbsp; private static List&lt;NameValuePair&gt; setHttpParams(Map&lt;String, String&gt; map) { &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; List&lt;NameValuePair&gt; formparams = new ArrayList&lt;NameValuePair&gt;(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; Set&lt;Map.Entry&lt;String, String&gt;&gt; set = map.entrySet(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; for (Map.Entry&lt;String, String&gt; entry : set) { &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; } &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; return formparams; &nbsp;</div><div>&nbsp; &nbsp; } &nbsp;<br /><br /><br /><br /><div>&nbsp;/**&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* 获得响应HTTP实体内容&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @param response&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @return&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @throws IOException&nbsp;</div><div>&nbsp; &nbsp; &nbsp;* @throws UnsupportedEncodingException&nbsp;</div><div>&nbsp; &nbsp; &nbsp;*/ &nbsp;</div><div>&nbsp; &nbsp; private static String GetHttpEntityContent(HttpResponse response) &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws IOException, UnsupportedEncodingException { &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; HttpEntity entity = response.getEntity(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; if (entity != null) { &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStream is = entity.getContent(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String line = br.readLine(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; StringBuilder sb = new StringBuilder(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (line != null) { &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(line + "\n"); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; line = br.readLine(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return sb.toString(); &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; } &nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; return ""; &nbsp;</div><div>&nbsp; &nbsp; } &nbsp;</div><div></div></div><img src ="http://www.blogjava.net/stevenjohn/aggbug/398117.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-04-20 00:54 <a href="http://www.blogjava.net/stevenjohn/archive/2013/04/20/398117.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete</title><link>http://www.blogjava.net/stevenjohn/archive/2013/04/19/398115.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Fri, 19 Apr 2013 15:39:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/04/19/398115.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/398115.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/04/19/398115.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/398115.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/398115.html</trackback:ping><description><![CDATA[<p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">逻辑：</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">String url = "http://www.baidu.com";</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">//将要访问的url字符串放入HttpPost中</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">HttpPost httpPost = new HttpPost(url);</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">//请求头 放置一些修改http请求头和cookie</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">httpPost.setHeader("Accept", "application/json");</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">......</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">//如果是HttpPost或者HttpPut请求需要在请求里加参数，而HttpGet或者HttpDelete请求则可以直接拼接到url字符串后面</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">//向HttpPost中加入参数</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">List&lt;NameValuePair&gt; values = new ArrayList&lt;NameValuePair&gt;();</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">values.add(new NameValuePair("id", "1"));</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">values.add(new NameValuePair("name", "xiaohong"));</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">httpPost.setEntity(new UrlEncodeFormEntity(values, HTTP.UTF_8)); &nbsp;//进行转码</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">&nbsp;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">//实例HttpClient 并执行带有HttpPost的方法,返回HttpResponse 响应，再进行操作</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">HttpClient httpClient = new DefaultHttpClient();</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">HttpResponse httpResponse = httpClient.execute(httpPost);</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">int statusCode = httpResponse.getStatusLine().getStatusCode(); &nbsp;//返回状态码 ，用来进行识别或者判断访问结果</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">if(statusCode == 200){</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">　　Instream in = httpResponse.getEntity().getContent();&nbsp; //要处理该数据流是否为GZIP流</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">&nbsp;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">&nbsp;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">示例代码如下：</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">package cn.dratek.haoyingsheng.manager.client;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">import cn.dratek.haoyingsheng.manager.util.ResourceUtil;<br />import net.dratek.browser.http.Cookie;<br />import net.dratek.browser.http.CookieManager;<br />import net.dratek.browser.http.URL;<br />import org.apache.http.*;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpDelete;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.client.methods.HttpPut;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.protocol.HTTP;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">import java.io.IOException;<br />import java.io.InputStream;<br />import java.io.UnsupportedEncodingException;<br />import java.util.List;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;"><br />public class HttpNetClient {<br />/**<br />* 所有get 请求底层调用方法<br />*<br />* @param url 请求url<br />* @return byte[] response data<br />*/<br />public static byte[] doGet(String url) {<br />InputStream in;<br />byte[] bre = null;<br />HttpResponse response;<br />CookieManager manager = CookieManager.getInstance();<br />if (url != null &amp;&amp; url.length() != 0) {<br />URL myURL = URL.parseString(url);<br />Cookie[] cookies = manager.getCookies(myURL);<br />HttpGet httpGet = new HttpGet(url);<br />if (cookies != null &amp;&amp; cookies.length &gt; 0) {<br />StringBuilder sb = new StringBuilder();<br />for (Cookie ck : cookies) {<br />sb.append(ck.name).append('=').append(ck.value).append(";");<br />}<br />String sck = sb.toString();<br />if (sck.length() &gt; 0) {<br />httpGet.setHeader("Cookie", sck);<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br />httpGet.setHeader("Accept-Encoding", "gzip, deflate");<br />httpGet.setHeader("Accept-Language", "zh-CN");<br />httpGet.setHeader("Accept", "application/json, application/xml, text/html, text/*, image/*, */*");<br />try {<br />response = new DefaultHttpClient().execute(httpGet);<br />if (response != null) {<br />int statusCode = response.getStatusLine().getStatusCode();<br />if (statusCode == 200 || statusCode == 403) {<br />Header[] headers = response.getHeaders("Set-Cookie");<br />if (headers != null &amp;&amp; headers.length &gt; 0) {<br />for (Header header : headers) {<br />manager.setCookie(myURL, header.getValue());<br />}<br />}<br />in = response.getEntity().getContent();<br />if (in != null) {<br />bre = ResourceUtil.readStream(in);<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;"><br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;"><br />return bre;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">/**<br />* 所有Post 请求底层调用方法<br />*<br />* @param url 请求url<br />* @param values 传递的参数<br />* @return byte[] 返回数据 or null<br />*/<br />public static byte[] doPost(String url, List&lt;NameValuePair&gt; values) {<br />System.out.println("url = " + url);<br />byte[] bytes = null;<br />HttpResponse response;<br />InputStream inputStream = null;<br />CookieManager manager = CookieManager.getInstance();<br />if (url != null &amp;&amp; url.length() != 0) {<br />URL myurl = URL.parseString(url);<br />Cookie[] cookies = manager.getCookies(myurl);<br />HttpPost post = new HttpPost(url);<br />if (cookies != null &amp;&amp; cookies.length &gt; 0) {<br />StringBuilder sb = new StringBuilder();<br />for (Cookie ck : cookies) {<br />sb.append(ck.name).append('=').append(ck.value).append(";");<br />}<br />String sck = sb.toString();<br />if (sck.length() &gt; 0) {<br />post.setHeader("Cookie", sck);<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br />post.setHeader("Accept-Encoding", "gzip, deflate");<br />post.setHeader("Accept-Language", "zh-CN");<br />post.setHeader("Accept", "application/json, application/xml, text/html, text/*, image/*, */*");<br />DefaultHttpClient client = new DefaultHttpClient();<br />try {<br />if (values != null &amp;&amp; values.size() &gt; 0) {<br />post.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8));<br />}<br />response = client.execute(post);<br />if (response != null) {<br />int statusCode = response.getStatusLine().getStatusCode();<br />if (statusCode == 200 || statusCode == 403) {<br />Header[] headers = response.getHeaders("Set-Cookie");<br />if (headers != null &amp;&amp; headers.length &gt; 0) {<br />for (Header header : headers) {<br />manager.setCookie(myurl, header.getValue());<br />}<br />}<br />inputStream = response.getEntity().getContent();<br />}<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">} catch (UnsupportedEncodingException e) {<br />e.printStackTrace();<br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br />if (inputStream != null) {<br />bytes = ResourceUtil.readStream(inputStream);<br />}<br />}<br />return bytes;<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">/**<br />* PUT基础请求<br />*<br />* @param url 请求地址<br />* @param values 提交参数<br />* @return byte[] 请求成功后的结果<br />*/<br />public static byte[] doPut(String url, List&lt;NameValuePair&gt; values) {<br />byte[] ret = null;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">CookieManager manager = CookieManager.getInstance();<br />if (url != null &amp;&amp; url.length() &gt; 0) {<br />URL myUrl = URL.parseString(url);<br />StringBuilder sb = new StringBuilder();<br />Cookie[] cookies = manager.getCookies(myUrl);<br />if (cookies != null &amp;&amp; cookies.length &gt; 0) {<br />for (Cookie cookie : cookies) {<br />sb.append(cookie.name).append("=").append(cookie.value).append(";");<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br />HttpPut request = new HttpPut(url);<br />String sck = sb.toString();<br />if (sck.length() &gt; 0) {<br />request.setHeader("Cookie", sck);<br />}<br />request.setHeader("Accept-Encoding", "gzip, deflate");<br />request.setHeader("Accept-Language", "zh-CN");<br />request.setHeader("Accept", "application/json, application/xml, text/html, text/*, image/*, */*");</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">DefaultHttpClient client = new DefaultHttpClient();<br />if (values != null &amp;&amp; values.size() &gt; 0) {<br />try {<br />UrlEncodedFormEntity entity;<br />entity = new UrlEncodedFormEntity(values);<br />request.setEntity(entity);<br />} catch (UnsupportedEncodingException e) {<br />e.printStackTrace();<br />}<br />}<br />try {<br />HttpResponse response = client.execute(request);<br />if (response != null) {<br />StatusLine statusLine = response.getStatusLine();<br />int statusCode = statusLine.getStatusCode();<br />if (statusCode == 200 || statusCode == 403) {<br />Header[] headers = response.getHeaders("Set-Cookie");<br />if (headers != null &amp;&amp; headers.length &gt; 0) {<br />for (Header header : headers) {<br />manager.setCookie(myUrl, header.getValue());<br />}<br />}<br />HttpEntity entity = response.getEntity();<br />InputStream inputStream = entity.getContent();<br />if (inputStream != null) {<br />ret = ResourceUtil.readStream(inputStream);<br />inputStream.close();<br />}<br />}<br />}<br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br />}<br />return ret;<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">/**<br />* Delete基础请求<br />*<br />* @param url 请求地址<br />* @return 请求成功后的结果<br />*/<br />public static byte[] doDelete(String url) {</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">InputStream in;<br />byte[] bre = null;<br />HttpResponse response;<br />CookieManager manager = CookieManager.getInstance();<br />if (url != null &amp;&amp; url.length() != 0) {<br />URL myurl = URL.parseString(url);<br />Cookie[] cookies = manager.getCookies(myurl);<br />HttpDelete delete = new HttpDelete(url);<br />if (cookies != null &amp;&amp; cookies.length &gt; 0) {<br />StringBuilder sb = new StringBuilder();<br />for (Cookie ck : cookies) {<br />sb.append(ck.name).append('=').append(ck.value).append(";");<br />}<br />String sck = sb.toString();<br />if (sck.length() &gt; 0) {<br />delete.setHeader("Cookie", sck);<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br />delete.setHeader("Accept-Encoding", "gzip, deflate");<br />delete.setHeader("Accept-Language", "zh-CN");<br />delete.setHeader("Accept", "application/json, application/xml, text/html, text/*, image/*, */*");<br />try {<br />response = new DefaultHttpClient().execute(delete);<br />if (response != null) {<br />int statusCode = response.getStatusLine().getStatusCode();<br />if (statusCode == 200 || statusCode == 403) {<br />Header[] headers = response.getHeaders("Set-Cookie");<br />if (headers != null &amp;&amp; headers.length &gt; 0) {<br />for (Header header : headers) {<br />manager.setCookie(myurl, header.getValue());<br />}<br />}<br />in = response.getEntity().getContent();<br />if (in != null) {<br />bre = ResourceUtil.readStream(in);<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;"><br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;"><br />return bre;<br />}</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">&nbsp;</p><p style="font-size: 13px; margin-top: 10px; margin-bottom: 10px; color: #4b4b4b; font-family: verdana, Arial, helvetica, sans-seriff; line-height: 19px; background-color: #ffffff;">}<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><div>http://www.cnblogs.com/lianghui66/archive/2013/03/06/2946495.html</div><br /></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/398115.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-04-19 23:39 <a href="http://www.blogjava.net/stevenjohn/archive/2013/04/19/398115.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 模拟form调用接口,自己添加header和body</title><link>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398053.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Thu, 18 Apr 2013 12:57:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398053.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/398053.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398053.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/398053.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/398053.html</trackback:ping><description><![CDATA[<p>package com.abin.lee.hack;</p>
<p>import java.io.BufferedInputStream;</p>
<p>import org.apache.http.HttpHost;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.entity.StringEntity;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.junit.Test;</p>
<p>public class HttpClientVisitTest {</p>
<p>&nbsp;private static final String HttpUrl = "<a href="http://42.120.20.61/toupiao/tp4.aspx">http://111.111.111.111/vote/ticket</a>";<br />&nbsp;private static final String HttpHost = "<u><font color="#0066cc">111.111.111.111</font></u>";<br />&nbsp;@Test<br />&nbsp;public void testHttpClientVisit() {<br />&nbsp;&nbsp;HttpClient httpClient = new DefaultHttpClient();<br />&nbsp;&nbsp;HttpPost httpPost = new HttpPost(HttpUrl);<br />&nbsp;&nbsp;httpPost.addHeader("Accept", "*/*");<br />&nbsp;&nbsp;httpPost.addHeader("Accept-Language", "zh-cn");<br />&nbsp;&nbsp;httpPost.addHeader("Referer", HttpUrl);<br />&nbsp;&nbsp;httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");<br />&nbsp;&nbsp;httpPost.addHeader("Cache-Control", "no-cache");<br />&nbsp;&nbsp;httpPost.addHeader("Accept-Encoding", "gzip, deflate");<br />&nbsp;&nbsp;httpPost.addHeader("User-Agent",<br />&nbsp;&nbsp;&nbsp;&nbsp;"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");<br />&nbsp;&nbsp;httpPost.addHeader("Host", HttpHost);<br />&nbsp;&nbsp;httpPost.addHeader("Connection", "Keep-Alive");<br />//&nbsp;&nbsp;HttpHost httpProxy = new HttpHost("222.222.222.222", 1443, "http");<br />//&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.DEFAULT_PROXY,httpProxy);<br />&nbsp;&nbsp;StringBuffer params = new StringBuffer();<br />&nbsp;&nbsp;String&nbsp;userName = "abin";<br />&nbsp;&nbsp;String passWord= "varyall";<br />&nbsp;&nbsp;String userAge= "12345";<br />&nbsp;&nbsp;String homeTown= "china beijing";<br />&nbsp;&nbsp;params.append("__userName ").append("=").append(userName )<br />&nbsp;&nbsp;&nbsp;&nbsp;.append("&amp;").append(passWord").append("=")<br />&nbsp;&nbsp;&nbsp;&nbsp;.append(passWord).append("&amp;").append("userAge")<br />&nbsp;&nbsp;&nbsp;&nbsp;.append("=").append(userAge).append("&amp;")<br />&nbsp;&nbsp;&nbsp;&nbsp;.append("homeTown").append("=")<br />&nbsp;&nbsp;&nbsp;&nbsp;.append(homeTown);<br />&nbsp;&nbsp;HttpResponse httpResponse = null;<br />&nbsp;&nbsp;String result = "";<br />&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;StringEntity reqEntity = new StringEntity(params.toString());<br />&nbsp;&nbsp;&nbsp;httpPost.setEntity(reqEntity);<br />&nbsp;&nbsp;&nbsp;HttpHost httpTarget = new HttpHost(HttpHost, 80, "http");<br />&nbsp;&nbsp;&nbsp;httpResponse = httpClient.execute(httpTarget, httpPost);<br />&nbsp;&nbsp;&nbsp;System.out.println("httpResponse=" + httpResponse.getStatusLine());</p>
<p>&nbsp;&nbsp;&nbsp;BufferedInputStream buffer = new BufferedInputStream(httpResponse<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.getEntity().getContent());<br />&nbsp;&nbsp;&nbsp;byte[] bytes = new byte[1024];<br />&nbsp;&nbsp;&nbsp;int line = 0;<br />&nbsp;&nbsp;&nbsp;StringBuilder builder = new StringBuilder();<br />&nbsp;&nbsp;&nbsp;while ((line = buffer.read(bytes)) != -1) {<br />&nbsp;&nbsp;&nbsp;&nbsp;builder.append(new String(bytes, 0, line));<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;result = new String(builder.toString());<br />&nbsp;&nbsp;} catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;if (httpPost.isAborted()) {<br />&nbsp;&nbsp;&nbsp;&nbsp;httpPost.abort();<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;}<br />//&nbsp;&nbsp; System.out.println("result="+result);</p>
<p>&nbsp;}</p>
<p>}<br /></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/398053.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-04-18 20:57 <a href="http://www.blogjava.net/stevenjohn/archive/2013/04/18/398053.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient Get代理访问</title><link>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398049.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Thu, 18 Apr 2013 09:50:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398049.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/398049.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398049.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/398049.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/398049.html</trackback:ping><description><![CDATA[//研究了一下午，终于发现一个问题，写这个代码不是很难的，难的是找一个能代理的IP地址，实际网上的好多代码都可以用滴，只是代理IP和Port有问题而已，废话少说，直接上代码：<br />1、先说Get的代理（首先提供一个Servlet的Get的http服务）<br />
<p>package com.abin.lee.servlet;</p>
<p>import javax.servlet.ServletConfig;<br />import javax.servlet.ServletException;<br />import javax.servlet.ServletOutputStream;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />import java.io.BufferedWriter;<br />import java.io.IOException;<br />import java.io.OutputStreamWriter;</p>
<p>/**<br />&nbsp;* Created with IntelliJ IDEA.<br />&nbsp;* User: abin<br />&nbsp;* Date: 13-4-18<br />&nbsp;* Time: 上午8:39<br />&nbsp;* To change this template use File | Settings | File Templates.<br />&nbsp;*/<br />public class HttpClientGetProxyServlet extends HttpServlet {<br />&nbsp;&nbsp;&nbsp; public void init(ServletConfig config) throws ServletException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; super.init(config);<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("receive httpGet request");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String userName=request.getParameter("userName");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String passWord=request.getParameter("passWord");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String localIp=request.getLocalAddr();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String localName=request.getLocalName();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int localPort=request.getLocalPort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int ServerPort=request.getServerPort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String leeHeader=request.getHeader("lee");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("userName="+userName+",passWord="+passWord+",localIp="+localIp+",localName="+localName+",localPort="+localPort);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("ServerPort="+ServerPort+",leeHeader="+leeHeader);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String remoteIp=request.getRemoteAddr();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String remoteHost=request.getRemoteHost();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int remotePort=request.getRemotePort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("remoteIp="+remoteIp+",remoteHost="+remoteHost+",remotePort="+remotePort);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ServletOutputStream out=response.getOutputStream();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; writer.write("success");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; writer.flush();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; writer.close();</p>
<p>&nbsp;&nbsp;&nbsp; }<br />}<br /></p><br /><br /><br />HttpGet代理测试类：<br />
<p>package com.abin.lee.ssh.senior.proxy.httpclient;<br />import org.apache.http.Header;<br />import org.apache.http.HttpEntity;<br />import org.apache.http.HttpHost;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.conn.params.ConnRoutePNames;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.util.EntityUtils;<br />import org.junit.Test;</p>
<p>public class HttpClientGetProxyServletTest {<br />&nbsp;public static final String HttpGetProxyUrl="<a href="http://localhost:8100/MyThread/HttpClientGetProxyServlet">http://localhost:8100/MyThread/HttpClientGetProxyServlet</a>";<br />&nbsp;@Test<br />&nbsp;&nbsp;&nbsp; public&nbsp; void testHttpClientPostProxyServlet()throws Exception {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpHost proxy = new HttpHost("10.10.10.10", 1443, "http");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DefaultHttpClient httpclient = new DefaultHttpClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpHost target = new HttpHost("localhost", 8100, "http");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet request = new HttpGet(HttpGetProxyUrl+"?"+"userName=abin&amp;passWord=varyall");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request.setHeader("lee", "lee");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("executing request to " + target + " via " + proxy);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse rsp = httpclient.execute(target, request);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpEntity entity = rsp.getEntity();</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("----------------------------------------");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(rsp.getStatusLine());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Header[] headers = rsp.getAllHeaders();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i&lt;headers.length; i++) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(headers[i]);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("----------------------------------------");</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (entity != null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(EntityUtils.toString(entity));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // When HttpClient instance is no longer needed,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // shut down the connection manager to ensure<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // immediate deallocation of all system resources<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br />}<br /></p><br /><br /><br /><br /><br /><br />//正常测试代码，非代理<br /><br />
<p>package com.abin.lee.ssh.senior.proxy.httpclient;</p>
<p>import java.io.BufferedReader;<br />import java.io.InputStreamReader;</p>
<p>import org.apache.http.HttpEntity;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.entity.StringEntity;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.junit.Test;</p>
<p>public class HttpClientGetServletTest {<br />&nbsp;public static final String HttpGetUrl = "<a href="http://localhost:8100/MyThread/HttpClientGetProxyServlet">http://localhost:8100/MyThread/HttpClientGetProxyServlet</a>";</p>
<p>&nbsp;@Test<br />&nbsp;public void HttpClientGetServlet() {<br />&nbsp;&nbsp;HttpClient httpClient = new DefaultHttpClient();<br />&nbsp;&nbsp;StringEntity reqEntity = null;<br />&nbsp;&nbsp;HttpGet httpGet = null;<br />&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;HttpGet request = new HttpGet(HttpGetUrl+"?"+"userName=abin&amp;passWord=varyall");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request.setHeader("lee", "lee");<br />&nbsp;&nbsp;&nbsp;// 目标地址<br />&nbsp;&nbsp;&nbsp;System.out.println("请求: " + httpGet.getRequestLine());<br />&nbsp;&nbsp;&nbsp;// 执行<br />&nbsp;&nbsp;&nbsp;HttpResponse response = httpClient.execute(httpGet);<br />&nbsp;&nbsp;&nbsp;HttpEntity entity = response.getEntity();<br />&nbsp;&nbsp;&nbsp;System.out.println("----------------------------------------");<br />&nbsp;&nbsp;&nbsp;System.out.println(response.getStatusLine());<br />&nbsp;&nbsp;&nbsp;if (entity != null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;System.out.println("Response content length: "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ entity.getContentLength());<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;// 显示结果<br />&nbsp;&nbsp;&nbsp;BufferedReader reader = new BufferedReader(new InputStreamReader(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;entity.getContent(), "UTF-8"));<br />&nbsp;&nbsp;&nbsp;String line = null;<br />&nbsp;&nbsp;&nbsp;while ((line = reader.readLine()) != null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(line);<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;} catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;if (!httpGet.isAborted()) {<br />&nbsp;&nbsp;&nbsp;&nbsp;httpGet.abort();<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;}<br />&nbsp;}<br />}<br /></p><br /><br /><br />//servlet配置<br /><br />&nbsp;&nbsp; &lt;servlet&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;HttpClientGetProxyServlet&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-class&gt;com.abin.lee.servlet.HttpClientGetProxyServlet&lt;/servlet-class&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/servlet&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-mapping&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;HttpClientGetProxyServlet&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;/HttpClientGetProxyServlet&lt;/url-pattern&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/servlet-mapping&gt;<br /><br /><br /><br /><br /><br /><br />我这里的IP和端口不一定能用哟，自己找能用的！！代码是100%没问题的，经过生产环境测试的哟！！！<img src ="http://www.blogjava.net/stevenjohn/aggbug/398049.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-04-18 17:50 <a href="http://www.blogjava.net/stevenjohn/archive/2013/04/18/398049.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient Post代理访问</title><link>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398048.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Thu, 18 Apr 2013 09:45:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398048.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/398048.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/04/18/398048.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/398048.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/398048.html</trackback:ping><description><![CDATA[<div>//研究了一下午，终于发现一个问题，写这个代码不是很难的，难的是找一个能代理的IP地址，实际网上的好多代码都可以用滴，只是代理IP和Port有问题而已，废话少说，直接上代码：<br />1、先说Post的代理<br />//HttpClientPostProxyServlet <br />
<p>package com.abin.lee.servlet;</p>
<p>import javax.servlet.ServletConfig;<br />import javax.servlet.ServletException;<br />import javax.servlet.ServletOutputStream;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />import java.io.BufferedWriter;<br />import java.io.IOException;<br />import java.io.OutputStreamWriter;</p>
<p>/**<br />&nbsp;* Created with IntelliJ IDEA.<br />&nbsp;* User: abin<br />&nbsp;* Date: 13-4-18<br />&nbsp;* Time: 上午8:39<br />&nbsp;* To change this template use File | Settings | File Templates.<br />&nbsp;*/<br />public class HttpClientPostProxyServlet extends HttpServlet {<br />&nbsp;&nbsp;&nbsp; public void init(ServletConfig config) throws ServletException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; super.init(config);<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("receive httpPost request");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String userName=request.getParameter("userName");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String passWord=request.getParameter("passWord");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String localIp=request.getLocalAddr();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String localName=request.getLocalName();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int localPort=request.getLocalPort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int serverPort=request.getServerPort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String leeHeader=request.getHeader("lee");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("userName="+userName+",passWord="+passWord+",localIp="+localIp+",localName="+localName+",localPort="+localPort);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("serverPort="+serverPort+",leeHeader="+leeHeader);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String remoteIp=request.getRemoteAddr();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String remoteHost=request.getRemoteHost();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int remotePort=request.getRemotePort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String remoteUser=request.getRemoteUser();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("remoteIp="+remoteIp+",remoteHost="+remoteHost+",remotePort="+remotePort+",remoteUser="+remoteUser);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ServletOutputStream out=response.getOutputStream();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; writer.write("success");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; writer.flush();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; writer.close();</p>
<p>&nbsp;&nbsp;&nbsp; }<br />}<br /></p><br /><br /><br />Post代理测试类：<br />//HttpClientPostProxyServletTest.java<br />
<p>package com.abin.lee.ssh.senior.proxy.httpclient;<br />import org.apache.http.Header;<br />import org.apache.http.HttpEntity;<br />import org.apache.http.HttpHost;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.conn.params.ConnRoutePNames;<br />import org.apache.http.entity.StringEntity;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.util.EntityUtils;<br />import org.junit.Test;</p>
<p>public class HttpClientPostProxyServletTest {<br />&nbsp;public static final String HttpPostProxyUrl="<a href="http://localhost:8100/MyThread/HttpClientPostProxyServlet">http://localhost:8100/MyThread/HttpClientPostProxyServlet</a>";<br />&nbsp;@Test<br />&nbsp;&nbsp;&nbsp; public&nbsp; void testHttpClientPostProxyServlet()throws Exception {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpHost proxy = new HttpHost("10.10.10.10", 1443, "http");</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DefaultHttpClient httpclient = new DefaultHttpClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpHost target = new HttpHost("localhost", 8100, "http");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpPost request = new HttpPost(HttpPostProxyUrl);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; StringEntity reqEntity = new StringEntity("userName=abin&amp;passWord=varyall");&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; reqEntity.setContentType("application/x-www-form-urlencoded");&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request.setEntity(reqEntity);&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request.setHeader("lee", "lee");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("executing request to " + target + " via " + proxy);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse rsp = httpclient.execute(target, request);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpEntity entity = rsp.getEntity();</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("----------------------------------------");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(rsp.getStatusLine());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Header[] headers = rsp.getAllHeaders();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i&lt;headers.length; i++) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(headers[i]);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("----------------------------------------");</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (entity != null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(EntityUtils.toString(entity));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // When HttpClient instance is no longer needed,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // shut down the connection manager to ensure<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // immediate deallocation of all system resources<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br />}<br /></p><br /><br /><br />//正常测试代码，非代理<br />
<p>package com.abin.lee.ssh.senior.proxy.httpclient;</p>
<p>import java.io.BufferedReader;<br />import java.io.InputStreamReader;</p>
<p>import org.apache.http.HttpEntity;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.entity.StringEntity;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.junit.Test;</p>
<p>public class HttpClientPostServletTest {<br />&nbsp;public static final String HttpPostUrl="<a href="http://localhost:8100/MyThread/HttpClientPostProxyServlet">http://localhost:8100/MyThread/HttpClientPostProxyServlet</a>";<br />&nbsp;@Test<br />&nbsp;public void testHttpClientPostServlet(){<br />&nbsp;&nbsp; HttpClient httpClient = new DefaultHttpClient();<br />&nbsp;&nbsp; HttpPost httpPost = new HttpPost(HttpPostUrl); <br />&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 目标地址&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("请求: " + httpPost.getRequestLine());&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 构造最简单的字符串数据&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; StringEntity reqEntity = new StringEntity("userName=abin&amp;passWord=varyall");&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 设置类型&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; reqEntity.setContentType("application/x-www-form-urlencoded");&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 设置请求的数据&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpPost.setEntity(reqEntity);&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpPost.setHeader("lee", "lee");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 执行&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse response = httpClient.execute(httpPost);&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpEntity entity = response.getEntity();&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("----------------------------------------");&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(response.getStatusLine());&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (entity != null) {&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Response content length: " + entity.getContentLength());&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 显示结果&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String line = null;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while ((line = reader.readLine()) != null) {&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(line);&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp; <br />&nbsp;&nbsp;} catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />&nbsp;&nbsp;}finally{<br />&nbsp;&nbsp;&nbsp;if(!httpPost.isAborted()){<br />&nbsp;&nbsp;&nbsp;&nbsp;httpPost.abort();<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;}<br />&nbsp;}<br />}<br /><br /><br /><br />//servlet配置<br />&nbsp; &lt;servlet&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;HttpClientPostProxyServlet&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-class&gt;com.abin.lee.servlet.HttpClientPostProxyServlet&lt;/servlet-class&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/servlet&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-mapping&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;HttpClientPostProxyServlet&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;/HttpClientPostProxyServlet&lt;/url-pattern&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/servlet-mapping&gt;<br /><br /><br /><br /><br />我这里的IP和端口不一定能用哟，自己找能用的！！代码是100%没问题的，经过生产环境测试的哟！！！</p></div><img src ="http://www.blogjava.net/stevenjohn/aggbug/398048.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-04-18 17:45 <a href="http://www.blogjava.net/stevenjohn/archive/2013/04/18/398048.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient访问单向https(不使用密钥库和信任库)</title><link>http://www.blogjava.net/stevenjohn/archive/2013/03/20/396760.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 20 Mar 2013 11:24:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/03/20/396760.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/396760.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/03/20/396760.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/396760.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/396760.html</trackback:ping><description><![CDATA[//客户端代码，用来测试访问Servlet：<br /><br />
<p>package com.abin.lee.ssh.basic.unionpay;</p>
<p>import java.io.BufferedInputStream;<br />import java.security.cert.CertificateException;<br />import java.security.cert.X509Certificate;<br />import java.text.SimpleDateFormat;<br />import java.util.ArrayList;<br />import java.util.List;</p>
<p>import javax.net.ssl.SSLContext;<br />import javax.net.ssl.SSLSocket;<br />import javax.net.ssl.TrustManager;<br />import javax.net.ssl.X509TrustManager;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.HttpVersion;<br />import org.apache.http.NameValuePair;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.client.params.AllClientPNames;<br />import org.apache.http.conn.scheme.Scheme;<br />import org.apache.http.conn.ssl.SSLSocketFactory;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.message.BasicNameValuePair;<br />import org.apache.http.params.BasicHttpParams;<br />import org.apache.http.params.HttpParams;<br />import org.apache.http.protocol.HTTP;<br />import org.junit.Test;</p>
<p>public class GetUnionpayMessages1Test {<br />&nbsp;private static final String HTTPURL = "<a href="https://124.207.105.27:1443/stsf/deal/unionpay/UnionPayDeal">https://124.288.188.28:1443/stsf/deal/unionpay/UnionPayDeal</a>";</p>
<p>&nbsp;@Test<br />&nbsp;public void testGetMessageState() throws Exception {<br />&nbsp;&nbsp;HttpClient httpClient = new DefaultHttpClient();<br />&nbsp;&nbsp;HttpPost httpPost = new HttpPost(HTTPURL);<br />&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.PROTOCOL_VERSION,<br />&nbsp;&nbsp;&nbsp;&nbsp;HttpVersion.HTTP_1_1);<br />&nbsp;&nbsp;httpClient.getParams().setParameter(<br />&nbsp;&nbsp;&nbsp;&nbsp;AllClientPNames.USE_EXPECT_CONTINUE, Boolean.TRUE);<br />&nbsp;&nbsp;httpClient.getParams().setParameter(<br />&nbsp;&nbsp;&nbsp;&nbsp;AllClientPNames.HTTP_CONTENT_CHARSET, "UTF_8");<br />&nbsp;&nbsp;httpClient.getParams().setParameter(<br />&nbsp;&nbsp;&nbsp;&nbsp;AllClientPNames.CONN_MANAGER_TIMEOUT, 10000l);<br />&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT,<br />&nbsp;&nbsp;&nbsp;&nbsp;2000);<br />&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 10000);<br />&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;TrustManager easyTrustManager = new X509TrustManager() {<br />&nbsp;&nbsp;&nbsp;&nbsp;public void checkClientTrusted(X509Certificate[] chain,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String authType) throws CertificateException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// 哦，这很简单！<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;public void checkServerTrusted(X509Certificate[] chain,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String authType) throws CertificateException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//哦，这很简单！<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;public X509Certificate[] getAcceptedIssuers() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;};<br />&nbsp;&nbsp;&nbsp;SSLContext sslcontext = SSLContext.getInstance("TLS");<br />&nbsp;&nbsp;&nbsp;sslcontext<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.init(null, new TrustManager[] { easyTrustManager }, null);<br />&nbsp;&nbsp;&nbsp;SSLSocketFactory sf = new SSLSocketFactory(sslcontext);<br />&nbsp;&nbsp;&nbsp;SSLSocket socket = (SSLSocket) sf.createSocket();<br />&nbsp;&nbsp;&nbsp;socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });<br />&nbsp;&nbsp;&nbsp;HttpParams params = new BasicHttpParams();<br />&nbsp;&nbsp;&nbsp;Scheme sch = new Scheme("https", 1443, sf);<br />&nbsp;&nbsp;&nbsp;sf.connectSocket(socket, "124.288.188.28", 1443, null, -1, params);</p>
<p>&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().getSchemeRegistry().register(sch);</p>
<p>&nbsp;&nbsp;&nbsp;List&lt;NameValuePair&gt; nvps = new ArrayList&lt;NameValuePair&gt;();<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("userName", "abin"));<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("createTime", new SimpleDateFormat(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"yyyy-MM-dd HH:mm:ss").format(new java.util.Date())));<br />&nbsp;&nbsp;&nbsp;HttpResponse httpResponse = null;<br />&nbsp;&nbsp;&nbsp;String result = "";<br />&nbsp;&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;&nbsp;httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));<br />&nbsp;&nbsp;&nbsp;&nbsp;httpResponse = httpClient.execute(httpPost);<br />&nbsp;&nbsp;&nbsp;&nbsp;BufferedInputStream buffer = new BufferedInputStream(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;httpResponse.getEntity().getContent());<br />&nbsp;&nbsp;&nbsp;&nbsp;byte[] bytes = new byte[1024];<br />&nbsp;&nbsp;&nbsp;&nbsp;int line = 0;<br />&nbsp;&nbsp;&nbsp;&nbsp;StringBuilder builder = new StringBuilder();<br />&nbsp;&nbsp;&nbsp;&nbsp;while ((line = buffer.read(bytes)) != -1) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;builder.append(new String(bytes, 0, line, "UTF-8"));<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;result = builder.toString();<br />&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;if (httpPost.isAborted()) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;httpPost.abort();<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;System.out.println("result=" + result);</p>
<p>&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;// When HttpClient instance is no longer needed,<br />&nbsp;&nbsp;&nbsp;// shut down the connection manager to ensure<br />&nbsp;&nbsp;&nbsp;// immediate deallocation of all system resources<br />&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;}<br />&nbsp;}<br />}<br /><br /><br /><br /><br /><br />//在%TOMCAT_HOME%/conf/server.xml里面添加的内容<br /><br />&lt;Connector port="1443" protocol="HTTP/1.1" SSLEnabled="true" <br />&nbsp;&nbsp;&nbsp;&nbsp; maxThreads="150" scheme="https" secure="true" <br />&nbsp;&nbsp;&nbsp;&nbsp; clientAuth="false" keystoreFile="D:/tomcat.keystore" <br />&nbsp;&nbsp;&nbsp;&nbsp; keystorePass="longcode" sslProtocol="TLS" /&gt; <br /><br /><br /><br /><br /><br />//UnionPayDeal.java<br /></p>
<p>import java.io.BufferedReader;<br />import java.io.IOException;<br />import java.io.InputStreamReader;</p>
<p>import javax.servlet.ServletConfig;<br />import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />/**<br />&nbsp;* <br />&nbsp;* @author Administrator<br />&nbsp;*<br />&nbsp;*/<br />public class UnionPayDeal extends HttpServlet {<br />&nbsp;private static final long serialVersionUID = -1370581177759574628L;</p>
<p>&nbsp;public void init(ServletConfig config) throws ServletException {<br />&nbsp;&nbsp;super.init(config);<br />&nbsp;}</p>
<p>&nbsp;public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{<br />&nbsp;&nbsp;System.out.println("接收到银联的异步通知");<br />&nbsp;&nbsp;String accept=null;<br />&nbsp;&nbsp;BufferedReader reader=new BufferedReader(new InputStreamReader(request.getInputStream()));<br />&nbsp;&nbsp;int num=0;<br />&nbsp;&nbsp;char[] buffer=new char[1024];<br />&nbsp;&nbsp;while((num=reader.read(buffer))!=-1){<br />&nbsp;&nbsp;&nbsp;accept=new String(buffer,0,num);<br />&nbsp;&nbsp;&nbsp;System.out.println("accept="+accept);<br />&nbsp;&nbsp;}<br />&nbsp;}<br />&nbsp;<br />&nbsp;<br />&nbsp;public void destroy() {<br />&nbsp;&nbsp;super.destroy();<br />&nbsp;}<br />}</p>
<p><br /></p>
<p>&nbsp;</p><img src ="http://www.blogjava.net/stevenjohn/aggbug/396760.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-03-20 19:24 <a href="http://www.blogjava.net/stevenjohn/archive/2013/03/20/396760.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 请求单向https（使用密钥库）</title><link>http://www.blogjava.net/stevenjohn/archive/2013/03/20/396759.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 20 Mar 2013 11:20:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/03/20/396759.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/396759.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/03/20/396759.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/396759.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/396759.html</trackback:ping><description><![CDATA[<p>//客户端代码，用来测试访问Servlet：<br /><br />package com.abin.lee.ssh.basic.https;</p>
<p>import java.io.BufferedInputStream;<br />import java.io.File;<br />import java.io.FileInputStream;<br />import java.security.KeyStore;<br />import java.text.SimpleDateFormat;<br />import java.util.ArrayList;<br />import java.util.List;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.HttpVersion;<br />import org.apache.http.NameValuePair;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.client.params.AllClientPNames;<br />import org.apache.http.conn.scheme.Scheme;<br />import org.apache.http.conn.ssl.SSLSocketFactory;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.message.BasicNameValuePair;<br />import org.apache.http.protocol.HTTP;<br />import org.junit.Test;</p>
<p>public class GetUnionpayMessageTest {<br />&nbsp;private static final String HTTPURL = "<a href="https://124.207.105.27:1443/stsf/deal/unionpay/UnionPayDeal">https://124.288.188.28:1443/stsf/deal/unionpay/UnionPayDeal</a>";</p>
<p>&nbsp;@Test<br />&nbsp;public void testGetMessageState() throws Exception {<br />&nbsp;&nbsp;HttpClient httpClient = new DefaultHttpClient();<br />&nbsp;&nbsp;HttpPost httpPost =new HttpPost(HTTPURL);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpClient.getParams().setParameter(AllClientPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpClient.getParams().setParameter(AllClientPNames.USE_EXPECT_CONTINUE, Boolean.TRUE);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpClient.getParams().setParameter(AllClientPNames.HTTP_CONTENT_CHARSET,"UTF_8");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpClient.getParams().setParameter(AllClientPNames.CONN_MANAGER_TIMEOUT, 10000l);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpClient.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 2000);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpClient.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 10000);<br />&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;KeyStore trustStore = KeyStore.getInstance(KeyStore<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.getDefaultType());<br />&nbsp;&nbsp;&nbsp;FileInputStream instream = new FileInputStream(new File(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"D:/tomcat.keystore"));<br />&nbsp;&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;&nbsp;trustStore.load(instream, "longcode".toCharArray());<br />&nbsp;&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;instream.close();<br />&nbsp;&nbsp;&nbsp;&nbsp;} catch (Exception ignore) {<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);<br />&nbsp;&nbsp;&nbsp;Scheme sch = new Scheme("https", 1443, socketFactory);<br />&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().getSchemeRegistry().register(sch);</p>
<p>&nbsp;&nbsp;&nbsp;List&lt;NameValuePair&gt; nvps = new ArrayList&lt;NameValuePair&gt;();<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("userName", "abin"));<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("createTime", new SimpleDateFormat(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"yyyy-MM-dd HH:mm:ss").format(new java.util.Date())));<br />&nbsp;&nbsp;&nbsp;HttpResponse httpResponse = null;<br />&nbsp;&nbsp;&nbsp;String result = "";<br />&nbsp;&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;&nbsp;httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));<br />&nbsp;&nbsp;&nbsp;&nbsp;httpResponse = httpClient.execute(httpPost);<br />&nbsp;&nbsp;&nbsp;&nbsp;BufferedInputStream buffer = new BufferedInputStream(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;httpResponse.getEntity().getContent());<br />&nbsp;&nbsp;&nbsp;&nbsp;byte[] bytes = new byte[1024];<br />&nbsp;&nbsp;&nbsp;&nbsp;int line = 0;<br />&nbsp;&nbsp;&nbsp;&nbsp;StringBuilder builder = new StringBuilder();<br />&nbsp;&nbsp;&nbsp;&nbsp;while ((line = buffer.read(bytes)) != -1) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;builder.append(new String(bytes, 0, line, "UTF-8"));<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;result = builder.toString();<br />&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;if (httpPost.isAborted()) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;httpPost.abort();<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;System.out.println("result=" + result);</p>
<p>&nbsp;&nbsp;} finally {<br />&nbsp;&nbsp;&nbsp;// When HttpClient instance is no longer needed,<br />&nbsp;&nbsp;&nbsp;// shut down the connection manager to ensure<br />&nbsp;&nbsp;&nbsp;// immediate deallocation of all system resources<br />&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;}<br />&nbsp;}<br />}<br /><br /><br /><br /><br />//在%TOMCAT_HOME%/conf/server.xml里面添加的内容<br /><br />&lt;Connector port="1443" protocol="HTTP/1.1" SSLEnabled="true" <br />&nbsp;&nbsp;&nbsp;&nbsp; maxThreads="150" scheme="https" secure="true" <br />&nbsp;&nbsp;&nbsp;&nbsp; clientAuth="false" keystoreFile="D:/tomcat.keystore" <br />&nbsp;&nbsp;&nbsp;&nbsp; keystorePass="longcode" sslProtocol="TLS" /&gt; <br /><br /><br /><br /><br /><br />//UnionPayDeal.java<br /></p>
<p>import java.io.BufferedReader;<br />import java.io.IOException;<br />import java.io.InputStreamReader;</p>
<p>import javax.servlet.ServletConfig;<br />import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />/**<br />&nbsp;* <br />&nbsp;* @author Administrator<br />&nbsp;*<br />&nbsp;*/<br />public class UnionPayDeal extends HttpServlet {<br />&nbsp;private static final long serialVersionUID = -1370581177759574628L;</p>
<p>&nbsp;public void init(ServletConfig config) throws ServletException {<br />&nbsp;&nbsp;super.init(config);<br />&nbsp;}</p>
<p>&nbsp;public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{<br />&nbsp;&nbsp;System.out.println("接收到银联的异步通知");<br />&nbsp;&nbsp;String accept=null;<br />&nbsp;&nbsp;BufferedReader reader=new BufferedReader(new InputStreamReader(request.getInputStream()));<br />&nbsp;&nbsp;int num=0;<br />&nbsp;&nbsp;char[] buffer=new char[1024];<br />&nbsp;&nbsp;while((num=reader.read(buffer))!=-1){<br />&nbsp;&nbsp;&nbsp;accept=new String(buffer,0,num);<br />&nbsp;&nbsp;&nbsp;System.out.println("accept="+accept);<br />&nbsp;&nbsp;}<br />&nbsp;}<br />&nbsp;<br />&nbsp;<br />&nbsp;public void destroy() {<br />&nbsp;&nbsp;super.destroy();<br />&nbsp;}<br />}</p>
<p><br />&nbsp;</p><img src ="http://www.blogjava.net/stevenjohn/aggbug/396759.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-03-20 19:20 <a href="http://www.blogjava.net/stevenjohn/archive/2013/03/20/396759.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpCLient4 Post请求</title><link>http://www.blogjava.net/stevenjohn/archive/2013/03/05/396068.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Tue, 05 Mar 2013 04:26:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/03/05/396068.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/396068.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/03/05/396068.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/396068.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/396068.html</trackback:ping><description><![CDATA[<p>package com.abin.lee.ssh.basic.train;</p>
<p>import java.io.BufferedInputStream;<br />import java.util.ArrayList;<br />import java.util.List;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.HttpVersion;<br />import org.apache.http.NameValuePair;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.client.params.AllClientPNames;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.message.BasicNameValuePair;<br />import org.apache.http.protocol.HTTP;<br />import org.junit.Test;</p>
<p>public class CityToCityTest {<br />&nbsp;private static final String HTTPURL="<a href="http://localhost:7500/train/mvc/train/searchTrain2">http://localhost:7500/train/mvc/train/searchTrain2</a>";<br />&nbsp;@Test<br />&nbsp;public void testCityToCity(){</p>
<p>&nbsp;&nbsp;&nbsp;HttpClient httpClient = new DefaultHttpClient();<br />&nbsp;&nbsp;&nbsp;HttpPost httpPost =new HttpPost(HTTPURL);<br />&nbsp;&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);<br />&nbsp;&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.USE_EXPECT_CONTINUE, Boolean.TRUE);<br />&nbsp;&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.HTTP_CONTENT_CHARSET,HTTP.UTF_8);<br />&nbsp;&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.CONN_MANAGER_TIMEOUT,1000l);<br />&nbsp;&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 2000);<br />&nbsp;&nbsp;&nbsp;httpClient.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 10000);<br />&nbsp;&nbsp;&nbsp;List&lt;NameValuePair&gt; nvps = new ArrayList&lt;NameValuePair&gt;();<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("terminalId", "132456"));<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("startCity", "北京"));<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("endCity", "上海"));<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("trainNumber", "T284"));<br />&nbsp;&nbsp;&nbsp;nvps.add(new BasicNameValuePair("searchType", "0"));<br />&nbsp;&nbsp;&nbsp;HttpResponse httpResponse =null;<br />&nbsp;&nbsp;&nbsp;String result="";<br />&nbsp;&nbsp;&nbsp;try {<br />&nbsp;&nbsp;&nbsp;&nbsp;httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));<br />&nbsp;&nbsp;&nbsp;&nbsp;httpResponse = httpClient.execute(httpPost);<br />&nbsp;&nbsp;&nbsp;&nbsp;BufferedInputStream buffer=new BufferedInputStream(httpResponse.getEntity().getContent());<br />&nbsp;&nbsp;&nbsp;&nbsp;byte[] bytes=new byte[1024];<br />&nbsp;&nbsp;&nbsp;&nbsp;int line=0;<br />&nbsp;&nbsp;&nbsp;&nbsp;StringBuilder builder=new StringBuilder();<br />&nbsp;&nbsp;&nbsp;&nbsp;while((line=buffer.read(bytes))!=-1){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;builder.append(new String(bytes,0,line,"UTF-8"));<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;result=builder.toString();<br />&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;}finally{<br />&nbsp;&nbsp;&nbsp;&nbsp;if(httpPost.isAborted()){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;httpPost.abort();<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;httpClient.getConnectionManager().shutdown();<br />&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;System.out.println("result="+result);<br />&nbsp;<br />&nbsp;}</p>
<p>}<br /></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/396068.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-03-05 12:26 <a href="http://www.blogjava.net/stevenjohn/archive/2013/03/05/396068.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Httpclient ConnectManager使用</title><link>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393997.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Tue, 08 Jan 2013 15:51:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393997.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/393997.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393997.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/393997.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/393997.html</trackback:ping><description><![CDATA[<p>package com.abin.lee.junit.httpasyncclient.example;</p>
<p>import java.util.List;<br />import java.util.concurrent.ExecutorService;<br />import java.util.concurrent.Executors;<br />&nbsp;<br />&nbsp;import org.apache.http.HttpEntity;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.conn.ClientConnectionManager;<br />import org.apache.http.conn.params.ConnManagerParams;<br />import org.apache.http.conn.scheme.PlainSocketFactory;<br />import org.apache.http.conn.scheme.Scheme;<br />import org.apache.http.conn.scheme.SchemeRegistry;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.impl.conn.PoolingClientConnectionManager;<br />import org.apache.http.params.BasicHttpParams;<br />import org.apache.http.params.HttpConnectionParams;<br />import org.apache.http.params.HttpParams;<br />import org.apache.http.protocol.BasicHttpContext;<br />import org.apache.http.protocol.HttpContext;<br />import org.apache.http.util.EntityUtils;<br />import org.junit.Test;<br />&nbsp;<br />&nbsp;public class ThreadPoolHttpClient {<br />&nbsp;&nbsp;&nbsp;&nbsp; // 线程池<br />&nbsp;&nbsp;&nbsp;&nbsp; private ExecutorService exe = null;<br />&nbsp;&nbsp;&nbsp;&nbsp; // 线程池的容量<br />&nbsp;&nbsp;&nbsp;&nbsp; private static final int POOL_SIZE = 20;<br />&nbsp;&nbsp;&nbsp;&nbsp; private HttpClient client = null;<br />&nbsp;&nbsp;&nbsp;&nbsp; String[] urls=null;<br />&nbsp;&nbsp;&nbsp;&nbsp; public ThreadPoolHttpClient(String[] urls){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.urls=urls;<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp; @Test<br />&nbsp;&nbsp;&nbsp;&nbsp; public void test() throws Exception {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; exe = Executors.newFixedThreadPool(POOL_SIZE);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpParams params =new BasicHttpParams();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* 从连接池中取连接的超时时间 */ <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ConnManagerParams.setTimeout(params, 1000);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* 连接超时 */ <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpConnectionParams.setConnectionTimeout(params, 2000); <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* 请求超时 */<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpConnectionParams.setSoTimeout(params, 4000);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SchemeRegistry schemeRegistry = new SchemeRegistry();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; schemeRegistry.register(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PoolingClientConnectionManager cm=new PoolingClientConnectionManager(schemeRegistry);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cm.setMaxTotal(10);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final HttpClient httpClient = new DefaultHttpClient(cm,params);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // URIs to perform GETs on<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final String[] urisToGet = urls;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* 有多少url创建多少线程，url多时机子撑不住<br />56&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // create a thread for each URI<br />57&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; GetThread[] threads = new GetThread[urisToGet.length];<br />58&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; threads.length; i++) {<br />59&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet httpget = new HttpGet(urisToGet[i]);<br />60&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threads[i] = new GetThread(httpClient, httpget);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />61&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />62&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // start the threads<br />63&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int j = 0; j &lt; threads.length; j++) {<br />64&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threads[j].start();<br />65&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />66 <br />67&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // join the threads，等待所有请求完成<br />68&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int j = 0; j &lt; threads.length; j++) {<br />69&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threads[j].join();<br />70&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />71&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 使用线程池*/<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; urisToGet.length; i++) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final int j=i;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(j);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet httpget = new HttpGet(urisToGet[i]);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; exe.execute( new GetThread(httpClient, httpget));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //创建线程池，每次调用POOL_SIZE<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /*<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; urisToGet.length; i++) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final int j=i;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(j);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; exe.execute(new Thread() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Override<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void run() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.setName("threadsPoolClient"+j);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.sleep(100);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(j);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (InterruptedException e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // TODO Auto-generated catch block<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet httpget = new HttpGet(urisToGet[j]);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new GetThread(httpClient, httpget).get();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; */<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //exe.shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Done");<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp; static class GetThread extends Thread{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private final HttpClient httpClient;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private final HttpContext context;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private final HttpGet httpget;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public GetThread(HttpClient httpClient, HttpGet httpget) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.httpClient = httpClient;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.context = new BasicHttpContext();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.httpget = httpget;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Override<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void run(){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.setName("threadsPoolClient");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Thread.sleep(5000);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (InterruptedException e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // TODO Auto-generated catch block<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void get() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse response = this.httpClient.execute(this.httpget, this.context);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpEntity entity = response.getEntity();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (entity != null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(this.httpget.getURI()+": status"+response.getStatusLine().toString());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // ensure the connection gets released to the manager<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EntityUtils.consume(entity);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (Exception ex) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.httpget.abort();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }finally{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpget.releaseConnection();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;}<br /></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/393997.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-01-08 23:51 <a href="http://www.blogjava.net/stevenjohn/archive/2013/01/08/393997.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpAsyncClient 异步HttpCLient(二) </title><link>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393996.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Tue, 08 Jan 2013 15:16:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393996.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/393996.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393996.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/393996.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/393996.html</trackback:ping><description><![CDATA[<p>package com.abin.lee.junit.httpasyncclient.service;</p>
<p>import java.io.BufferedWriter;<br />import java.io.IOException;<br />import java.io.OutputStreamWriter;<br />import java.util.Map;</p>
<p>import javax.servlet.ServletOutputStream;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;</p>
<p>public class HttpAsyncClientService extends HttpServlet{<br />&nbsp;private static final long serialVersionUID = 807336917776643578L;</p>
<p>&nbsp;@SuppressWarnings("rawtypes")<br />&nbsp;public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{<br />&nbsp;&nbsp;Map map=request.getParameterMap();<br />&nbsp;&nbsp;String id=(String)((Object[])map.get("id"))[0].toString();<br />&nbsp;&nbsp;if(null!=id&amp;&amp;!"".equals(id)){<br />&nbsp;&nbsp;&nbsp;String result=id+" is response";<br />&nbsp;&nbsp;&nbsp;System.out.println("result="+result);<br />&nbsp;&nbsp;&nbsp;ServletOutputStream out=response.getOutputStream();<br />&nbsp;&nbsp;&nbsp;BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));<br />&nbsp;&nbsp;&nbsp;writer.write(result);<br />&nbsp;&nbsp;&nbsp;writer.flush();<br />&nbsp;&nbsp;&nbsp;writer.close();<br />&nbsp;&nbsp;}else{<br />&nbsp;&nbsp;&nbsp;String result=id+" is null";<br />&nbsp;&nbsp;&nbsp;System.out.println("result="+result);<br />&nbsp;&nbsp;&nbsp;ServletOutputStream out=response.getOutputStream();<br />&nbsp;&nbsp;&nbsp;BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));<br />&nbsp;&nbsp;&nbsp;writer.write(result);<br />&nbsp;&nbsp;&nbsp;writer.flush();<br />&nbsp;&nbsp;&nbsp;writer.close();<br />&nbsp;&nbsp;}<br />&nbsp;}<br />}<br /></p><br /><br /><br /><br />&lt;servlet&gt;<br />&nbsp;&nbsp;&lt;servlet-name&gt;HttpAsyncClientService&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&lt;servlet-class&gt;com.abin.lee.junit.httpasyncclient.service.HttpAsyncClientService&lt;/servlet-class&gt;<br />&nbsp;&lt;/servlet&gt;<br />&nbsp;&lt;servlet-mapping&gt;<br />&nbsp;&nbsp;&lt;servlet-name&gt;HttpAsyncClientService&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&lt;url-pattern&gt;/HttpAsyncClientService&lt;/url-pattern&gt;<br />&nbsp;&lt;/servlet-mapping&gt;<br /><br /><br /><br /><br /><br /><br /><br />
<p>package com.abin.lee.junit.httpasyncclient.example;</p>
<p>import java.util.concurrent.CountDownLatch;<br />import java.util.concurrent.Future;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.concurrent.FutureCallback;<br />import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;<br />import org.apache.http.nio.client.HttpAsyncClient;<br />import org.apache.http.params.CoreConnectionPNames;<br />import org.apache.http.util.EntityUtils;</p>
<p>public class CreateAsyncClientHttpExchangeFutureCallback {<br />&nbsp; public static void main(String[] args) throws Exception {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpAsyncClient httpclient = new DefaultHttpAsyncClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.getParams()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.start();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet[] requests = new HttpGet[] {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new HttpGet("<a href="http://localhost:7000/global/HttpAsyncClientService?id=6">http://localhost:7000/global/HttpAsyncClientService?id=6</a>"),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new HttpGet("<a href="http://localhost:7000/global/HttpAsyncClientService?id=8">http://localhost:7000/global/HttpAsyncClientService?id=8</a>"),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new HttpGet("<a href="http://localhost:7000/global/HttpAsyncClientService?id=5">http://localhost:7000/global/HttpAsyncClientService?id=5</a>")<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final CountDownLatch latch = new CountDownLatch(requests.length);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (final HttpGet request: requests) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.execute(request, new FutureCallback&lt;HttpResponse&gt;() {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void completed(final HttpResponse response) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine() + "-&gt;" + response.getStatusLine());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void failed(final Exception ex) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine() + "-&gt;" + ex);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void cancelled() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine() + " cancelled");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Future&lt;HttpResponse&gt; future = httpclient.execute(request, null);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse response = future.get();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Response: " + response.getStatusLine());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Response1: " + EntityUtils.toString(response.getEntity()));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.await();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Shutting down");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Done");<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp; public static String AsyncHttp(){<br />&nbsp;&nbsp; <br />&nbsp;&nbsp; return null;<br />&nbsp; }<br />}<br /></p><br /><br /><br /><br /><br /><br /><br /><br /><img src ="http://www.blogjava.net/stevenjohn/aggbug/393996.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-01-08 23:16 <a href="http://www.blogjava.net/stevenjohn/archive/2013/01/08/393996.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpAsyncClient  异步HttpCLient(一)</title><link>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393995.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Tue, 08 Jan 2013 15:15:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393995.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/393995.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/01/08/393995.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/393995.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/393995.html</trackback:ping><description><![CDATA[<p>package com.abin.lee.junit.httpasyncclient.service;</p>
<p>import java.io.BufferedWriter;<br />import java.io.IOException;<br />import java.io.OutputStreamWriter;<br />import java.util.Map;</p>
<p>import javax.servlet.ServletOutputStream;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;</p>
<p>public class HttpAsyncClientService extends HttpServlet{<br />&nbsp;private static final long serialVersionUID = 807336917776643578L;</p>
<p>&nbsp;@SuppressWarnings("rawtypes")<br />&nbsp;public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{<br />&nbsp;&nbsp;Map map=request.getParameterMap();<br />&nbsp;&nbsp;String id=(String)((Object[])map.get("id"))[0].toString();<br />&nbsp;&nbsp;if(null!=id&amp;&amp;!"".equals(id)){<br />&nbsp;&nbsp;&nbsp;String result=id+" is response";<br />&nbsp;&nbsp;&nbsp;System.out.println("result="+result);<br />&nbsp;&nbsp;&nbsp;ServletOutputStream out=response.getOutputStream();<br />&nbsp;&nbsp;&nbsp;BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));<br />&nbsp;&nbsp;&nbsp;writer.write(result);<br />&nbsp;&nbsp;&nbsp;writer.flush();<br />&nbsp;&nbsp;&nbsp;writer.close();<br />&nbsp;&nbsp;}else{<br />&nbsp;&nbsp;&nbsp;String result=id+" is null";<br />&nbsp;&nbsp;&nbsp;System.out.println("result="+result);<br />&nbsp;&nbsp;&nbsp;ServletOutputStream out=response.getOutputStream();<br />&nbsp;&nbsp;&nbsp;BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));<br />&nbsp;&nbsp;&nbsp;writer.write(result);<br />&nbsp;&nbsp;&nbsp;writer.flush();<br />&nbsp;&nbsp;&nbsp;writer.close();<br />&nbsp;&nbsp;}<br />&nbsp;}<br />}<br /></p><br /><br /><br /><br /><br /><br /><br />&lt;servlet&gt;<br />&nbsp;&nbsp;&lt;servlet-name&gt;HttpAsyncClientService&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&lt;servlet-class&gt;com.abin.lee.junit.httpasyncclient.service.HttpAsyncClientService&lt;/servlet-class&gt;<br />&nbsp;&lt;/servlet&gt;<br />&nbsp;&lt;servlet-mapping&gt;<br />&nbsp;&nbsp;&lt;servlet-name&gt;HttpAsyncClientService&lt;/servlet-name&gt;<br />&nbsp;&nbsp;&lt;url-pattern&gt;/HttpAsyncClientService&lt;/url-pattern&gt;<br />&nbsp;&lt;/servlet-mapping&gt;<br /><br /><br /><br /><br /><br />
<p>package com.abin.lee.junit.httpasyncclient.example;</p>
<p>import java.util.concurrent.Future;</p>
<p>import org.apache.http.HttpResponse;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;<br />import org.apache.http.nio.client.HttpAsyncClient;<br />import org.apache.http.util.EntityUtils;</p>
<p>public class CreateHttpAsyncClient {<br />&nbsp;public static void main(String[] args) throws Exception {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpAsyncClient httpclient = new DefaultHttpAsyncClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.start();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet request = new HttpGet("<a href="http://localhost:7000/global/HttpAsyncClientService?id=5">http://localhost:7000/global/HttpAsyncClientService?id=5</a>");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Future&lt;HttpResponse&gt; future = httpclient.execute(request, null);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpResponse response = future.get();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Response: " + response.getStatusLine());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Response1: " + EntityUtils.toString(response.getEntity()));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Shutting down");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Done");<br />&nbsp;&nbsp;&nbsp; }</p>
<p>}<br /></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/393995.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-01-08 23:15 <a href="http://www.blogjava.net/stevenjohn/archive/2013/01/08/393995.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>多线程异步请求</title><link>http://www.blogjava.net/stevenjohn/archive/2013/01/07/393926.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Mon, 07 Jan 2013 13:14:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2013/01/07/393926.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/393926.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2013/01/07/393926.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/393926.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/393926.html</trackback:ping><description><![CDATA[View Code <br />&nbsp;package generate.httpclient;<br />&nbsp;<br />&nbsp;import java.io.ByteArrayOutputStream;<br />&nbsp;import java.io.IOException;<br />&nbsp;import java.io.InputStream;<br />&nbsp;import java.util.ArrayList;<br />&nbsp;import java.util.HashMap;<br />&nbsp;import java.util.List;<br />&nbsp;import java.util.Map;<br />&nbsp;import java.util.concurrent.CountDownLatch;<br />&nbsp;<br />&nbsp;import org.apache.http.HttpResponse;<br />&nbsp;import org.apache.http.client.methods.HttpGet;<br />&nbsp;import org.apache.http.concurrent.FutureCallback;<br />&nbsp;import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;<br />&nbsp;import org.apache.http.nio.client.HttpAsyncClient;<br />&nbsp;import org.apache.http.nio.reactor.IOReactorException;<br />&nbsp;<br />&nbsp;public class AsynClient{<br />&nbsp;&nbsp;&nbsp;&nbsp; /**<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * @param args<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * @throws IOReactorException<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * @throws InterruptedException<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; */<br />&nbsp;&nbsp;&nbsp;&nbsp; private List&lt;String&gt; urls;<br />&nbsp;&nbsp;&nbsp;&nbsp; private HandlerFailThread failHandler;<br />&nbsp;&nbsp;&nbsp;&nbsp; public AsynClient(List&lt;String&gt; list){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failHandler=new HandlerFailThread();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; urls=list;<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp; public Map&lt;String,String&gt; asynGet() throws IOReactorException,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; InterruptedException {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final HttpAsyncClient httpclient = new DefaultHttpAsyncClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.start();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int urlLength=urls.size();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpGet[] requests = new HttpGet[urlLength];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int i=0;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for(String url : urls){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; requests[i]=new HttpGet(url);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i++;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final CountDownLatch latch = new CountDownLatch(requests.length);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; final Map&lt;String, String&gt; responseMap=new HashMap&lt;String, String&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (final HttpGet request : requests) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.execute(request, new FutureCallback&lt;HttpResponse&gt;() {<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void completed(final HttpResponse response) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; responseMap.put(request.getURI().toString(), response.getStatusLine().toString());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(request.getRequestLine() + "-&gt;"<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; + response.getStatusLine()+"-&gt;");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //+readInputStream(response.getEntity().getContent())<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (IllegalStateException e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failHandler.putFailUrl(request.getURI().toString(),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; response.getStatusLine().toString());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failHandler.putFailUrl(request.getURI().toString(),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; response.getStatusLine().toString());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void failed(final Exception ex) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ex.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failHandler.putFailUrl(request.getURI().toString(),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ex.getMessage());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void cancelled() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.countDown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Doing...");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; latch.await();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; httpclient.shutdown();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Done");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failHandler.printFailUrl();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return responseMap;<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp; private String readInputStream(InputStream input) throws IOException{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; byte[] buffer = new byte[128];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int len = 0;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ByteArrayOutputStream bytes = new ByteArrayOutputStream();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while((len = input.read(buffer)) &gt;= 0) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bytes.write(buffer, 0, len);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return bytes.toString();<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp; /**<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * Test<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * @param args<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; */<br />&nbsp;&nbsp;&nbsp;&nbsp; public static void main(String[] args) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; List&lt;String&gt; urls=new ArrayList&lt;String&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; urls.add("<a href="http://127.0.0.1/examples/servlets/">http://127.0.0.1/examples/servlets/</a>");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; urls.add("<a href="http://127.0.0.1/examples/servlets/">http://127.0.0.1/examples/servlets/</a>");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; urls.add("<a href="http://127.0.0.1/examples/servlets/">http://127.0.0.1/examples/servlets/</a>");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for(int i=0;i&lt;10;i++){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; urls.addAll(urls);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(urls.size());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AsynClient client=new AsynClient(urls);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; client.asynGet();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (IOReactorException e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (InterruptedException e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.printStackTrace();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("done");<br />&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;}<img src ="http://www.blogjava.net/stevenjohn/aggbug/393926.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2013-01-07 21:14 <a href="http://www.blogjava.net/stevenjohn/archive/2013/01/07/393926.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient_4 用法 由HttpClient_3 升级到 HttpClient_4 必看 </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388609.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:46:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388609.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388609.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388609.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388609.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388609.html</trackback:ping><description><![CDATA[<div style="border-bottom: #bbbbbb 1px solid; border-left: #bbbbbb 1px solid; padding-bottom: 8px; background-color: #fffffa; padding-left: 8px; padding-right: 8px; font-family: Verdana, Arial, Tahoma, sans-serif; border-top: #bbbbbb 1px solid; border-right: #bbbbbb 1px solid; padding-top: 8px; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial" class="newspager_template">
<div style="text-align: left; line-height: normal; font-family: Verdana, Arial, Tahoma, sans-serif; font-size: large; font-weight: bold" class="f3"><span style="font-size: 13px; font-weight: normal" class="Apple-style-span">HttpClient程序包是一个实现了 HTTP 协议的客户端编程工具包，要想熟练的掌握它，必须熟悉 HTTP协议。一个最简单的调用如下：</span></div>
<div style="padding-bottom: 4px; line-height: normal; padding-left: 0px; padding-right: 0px; font-family: Verdana, Arial, Tahoma, sans-serif; word-wrap: break-word; font-size: 9.5pt; word-break: break-all; padding-top: 4px" class="inherit_c wrap_text">
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">import java.io.IOException;</div>
<div style="font-family: inherit">import org.apache.http.HttpResponse;</div>
<div style="font-family: inherit">import org.apache.http.client.ClientProtocolException;</div>
<div style="font-family: inherit">import org.apache.http.client.HttpClient;</div>
<div style="font-family: inherit">import org.apache.http.client.methods.HttpGet;</div>
<div style="font-family: inherit">import org.apache.http.client.methods.HttpUriRequest;</div>
<div style="font-family: inherit">import org.apache.http.impl.client.DefaultHttpClient;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">public class Test {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;public static void main(String[] args) {</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; // 核心应用类</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; HttpClient httpClient = new DefaultHttpClient();</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// HTTP请求</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpUriRequest request =</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new HttpGet("http://localhost/index.html");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 打印请求信息</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(request.getRequestLine());</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;try {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 发送请求，返回响应</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;HttpResponse response = httpClient.execute(request);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 打印响应信息</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(response.getStatusLine());</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} catch (ClientProtocolException e) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 协议错误</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} catch (IOException e) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 网络异常</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">如果HTTP服务器正常并且存在相应的服务，则上例会打印出两行结果：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;GET http://localhost/index.html HTTP/1.1</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;HTTP/1.1 200 OK&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">核心对象httpClient的调用非常直观，其execute方法传入一个request对象，返回一个response对象。使用 httpClient发出HTTP请求时，系统可能抛出两种异常，分别是ClientProtocolException和IOException。第一种异常的发生通常是协议错误导致，如在构造HttpGet对象时传入的协议不对（例如不小心将&#8221;http&#8221;写成&#8221;htp&#8221;），或者服务器端返回的内容不符合HTTP协议要求等；第二种异常一般是由于网络原因引起的异常，如HTTP服务器未启动等。</div>
<div style="font-family: inherit">从实际应用的角度看，HTTP协议由两大部分组成：HTTP请求和HTTP响应。那么HttpClient程序包是如何实现HTTP客户端应用的呢？实现过程中需要注意哪些问题呢？</div>
<div style="font-family: inherit">HTTP请求</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HTTP 1.1由以下几种请求组成：GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS， 程序包中分别用HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions 这几个类创建请求。所有的这些类均实现了HttpUriRequest接口，故可以作为execute的执行参数使用。</div>
<div style="font-family: inherit">所有请求中最常用的是GET与POST两种请求，与创建GET请求的方法相同，可以用如下方法创建一个POST请求：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpUriRequest request = new HttpPost(</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;"http://localhost/index.html");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HTTP请求格式告诉我们，有两个位置或者说两种方式可以为request提供参数：request-line方式与request-body方式。</div>
<div style="font-family: inherit">request-line</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">request-line方式是指在请求行上通过URI直接提供参数。</div>
<div style="font-family: inherit">（1）</div>
<div style="font-family: inherit">我们可以在生成request对象时提供带参数的URI，如：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpUriRequest request = new HttpGet(</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;"http://localhost/index.html?param1=value1&amp;param2=value2");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">（2）</div>
<div style="font-family: inherit">另外，HttpClient程序包为我们提供了URIUtils工具类，可以通过它生成带参数的URI，如：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">URI uri = URIUtils.createURI("http", "localhost", -1, "/index.html",</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;"param1=value1&amp;param2=value2", null);</div>
<div style="font-family: inherit">HttpUriRequest request = new HttpGet(uri);</div>
<div style="font-family: inherit">System.out.println(request.getURI());</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">上例的打印结果如下：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;http://localhost/index.html?param1=value1&amp;param2=value2</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">（3）</div>
<div style="font-family: inherit">需要注意的是，如果参数中含有中文，需将参数进行URLEncoding处理，如：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">String param = "param1=" + URLEncoder.encode("中国", "UTF-8") + "&amp;param2=value2";</div>
<div style="font-family: inherit">URI uri = URIUtils.createURI("http", "localhost", 8080,</div>
<div style="font-family: inherit">"/sshsky/index.html", param, null);</div>
<div style="font-family: inherit">System.out.println(uri);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">上例的打印结果如下：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&amp;param2=value2</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">（4）</div>
<div style="font-family: inherit">对于参数的URLEncoding处理，HttpClient程序包为我们准备了另一个工具类：URLEncodedUtils。通过它，我们可以直观的（但是比较复杂）生成URI，如：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">List params = new ArrayList();</div>
<div style="font-family: inherit">params.add(new BasicNameValuePair("param1", "中国"));</div>
<div style="font-family: inherit">params.add(new BasicNameValuePair("param2", "value2"));</div>
<div style="font-family: inherit">String param = URLEncodedUtils.format(params, "UTF-8");</div>
<div style="font-family: inherit">URI uri = URIUtils.createURI("http", "localhost", 8080,</div>
<div style="font-family: inherit">"/sshsky/index.html", param, null);</div>
<div style="font-family: inherit">System.out.println(uri);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">上例的打印结果如下：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&amp;param2=value2</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">request-body</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">与request-line方式不同，request-body方式是在request-body中提供参数，此方式只能用于POST请求。在 HttpClient程序包中有两个类可以完成此项工作，它们分别是UrlEncodedFormEntity类与MultipartEntity类。这两个类均实现了HttpEntity接口。</div>
<div style="font-family: inherit">（1）</div>
<div style="font-family: inherit">使用最多的是UrlEncodedFormEntity类。通过该类创建的对象可以模拟传统的HTML表单传送POST请求中的参数。如下面的表单：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&lt;form action="http://localhost/index.html" method="POST"&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;input type="text" name="param1" value="中国"/&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;input type="text" name="param2" value="value2"/&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;inupt type="submit" value="submit"/&gt;</div>
<div style="font-family: inherit">&lt;/form&gt;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">我们可以用下面的代码实现：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">List formParams = new ArrayList();</div>
<div style="font-family: inherit">formParams.add(new BasicNameValuePair("param1", "中国"));</div>
<div style="font-family: inherit">formParams.add(new BasicNameValuePair("param2", "value2"));</div>
<div style="font-family: inherit">HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpPost request = new HttpPost(&#8220;http://localhost/index.html&#8221;);</div>
<div style="font-family: inherit">request.setEntity(entity);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">当然，如果想查看HTTP数据格式，可以通过HttpEntity对象的各种方法取得。如：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">List formParams = new ArrayList();</div>
<div style="font-family: inherit">formParams.add(new BasicNameValuePair("param1", "中国"));</div>
<div style="font-family: inherit">formParams.add(new BasicNameValuePair("param2", "value2"));</div>
<div style="font-family: inherit">UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">System.out.println(entity.getContentType());</div>
<div style="font-family: inherit">System.out.println(entity.getContentLength());</div>
<div style="font-family: inherit">System.out.println(EntityUtils.getContentCharSet(entity));</div>
<div style="font-family: inherit">System.out.println(EntityUtils.toString(entity));</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">上例的打印结果如下：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;Content-Type: application/x-www-form-urlencoded; charset=UTF-8</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;39</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;UTF-8</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;param1=%E4%B8%AD%E5%9B%BD&amp;param2=value2&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">（2）</div>
<div style="font-family: inherit">除了传统的application/x-www-form-urlencoded表单，我们另一个经常用到的是上传文件用的表单，这种表单的类型为 multipart/form-data。在HttpClient程序扩展包（HttpMime）中专门有一个类与之对应，那就是 MultipartEntity类。此类同样实现了HttpEntity接口。如下面的表单：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&lt;form action="http://localhost/index.html" method="POST"</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;enctype="multipart/form-data"&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;input type="text" name="param1" value="中国"/&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;input type="text" name="param2" value="value2"/&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;input type="file" name="param3"/&gt;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;&lt;inupt type="submit" value="submit"/&gt;</div>
<div style="font-family: inherit">&lt;/form&gt;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">我们可以用下面的代码实现：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">MultipartEntity entity = new MultipartEntity();</div>
<div style="font-family: inherit">entity.addPart("param1", new StringBody("中国", Charset.forName("UTF-8")));</div>
<div style="font-family: inherit">entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")));</div>
<div style="font-family: inherit">entity.addPart("param3", new FileBody(new File("C:\\1.txt")));</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpPost request = new HttpPost(&#8220;http://localhost/index.html&#8221;);</div>
<div style="font-family: inherit">request.setEntity(entity);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HTTP响应</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpClient程序包对于HTTP响应的处理较之HTTP请求来说是简单多了，其过程同样使用了HttpEntity接口。我们可以从 HttpEntity对象中取出数据流（InputStream），该数据流就是服务器返回的响应数据。需要注意的是，HttpClient程序包不负责解析数据流中的内容。如：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpUriRequest request = ...;</div>
<div style="font-family: inherit">HttpResponse response = httpClient.execute(request);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">// 从response中取出HttpEntity对象</div>
<div style="font-family: inherit">HttpEntity entity = response.getEntity();</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">// 查看entity的各种指标</div>
<div style="font-family: inherit">System.out.println(entity.getContentType());</div>
<div style="font-family: inherit">System.out.println(entity.getContentLength());</div>
<div style="font-family: inherit">System.out.println(EntityUtils.getContentCharSet(entity));</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">// 取出服务器返回的数据流</div>
<div style="font-family: inherit">InputStream stream = entity.getContent();</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">// 以任意方式操作数据流stream</div>
<div style="font-family: inherit">// 调用方式 略</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">附注：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">本文说明的是HttpClient 4.0.1，该程序包（包括依赖的程序包）由以下几个JAR包组成：</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">commons-logging-1.1.1.jar</div>
<div style="font-family: inherit">commons-codec-1.4.jar</div>
<div style="font-family: inherit">httpcore-4.0.1.jar</div>
<div style="font-family: inherit">httpclient-4.0.1.jar</div>
<div style="font-family: inherit">apache-mime4j-0.6.jar</div>
<div style="font-family: inherit">httpmime-4.0.1.jar</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">可以在此处下载完整的JAR包。</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">现在Apache已经发布了：HttpCore 4.0-beta3、HttpClient 4.0-beta1。</div>
<div style="font-family: inherit">到此处可以去下载这些源代码：http://hc.apache.org/downloads.cgi</div>
<div style="font-family: inherit">另外，还需要apache-mime4j-0.5.jar 包。</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">在这里先写个简单的POST方法，中文资料不多，英文不太好。</div>
<div style="font-family: inherit">package test;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">import java.util.ArrayList;</div>
<div style="font-family: inherit">import java.util.List;</div>
<div style="font-family: inherit">import org.apache.http.Header;</div>
<div style="font-family: inherit">import org.apache.http.HttpEntity;</div>
<div style="font-family: inherit">import org.apache.http.HttpResponse;</div>
<div style="font-family: inherit">import org.apache.http.NameValuePair;</div>
<div style="font-family: inherit">import org.apache.http.client.entity.UrlEncodedFormEntity;</div>
<div style="font-family: inherit">import org.apache.http.client.methods.HttpPost;</div>
<div style="font-family: inherit">import org.apache.http.client.params.CookiePolicy;</div>
<div style="font-family: inherit">import org.apache.http.client.params.ClientPNames;</div>
<div style="font-family: inherit">import org.apache.http.impl.client.DefaultHttpClient;</div>
<div style="font-family: inherit">import org.apache.http.message.BasicNameValuePair;</div>
<div style="font-family: inherit">import org.apache.http.protocol.HTTP;</div>
<div style="font-family: inherit">import org.apache.http.util.EntityUtils;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">public class Test2 {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;public static void main(String[] args) throws Exception {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;DefaultHttpClient httpclient = new DefaultHttpClient(); &nbsp; &nbsp; &nbsp;//实例化一个HttpClient</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpResponse response = null;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpEntity entity = null;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;httpclient.getParams().setParameter(</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); &nbsp;//设置cookie的兼容性</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpPost httpost = new HttpPost("http://127.0.0.1:8080/pub/jsp/getInfo"); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //引号中的参数是：servlet的地址</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;List &lt;NameValuePair&gt; nvps = new ArrayList &lt;NameValuePair&gt;(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;nvps.add(new BasicNameValuePair("jqm", "fb1f7cbdaf2bf0a9cb5d43736492640e0c4c0cd0232da9de")); &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// &nbsp; BasicNameValuePair("name", "value"), name是post方法里的属性, value是传入的参数值</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;nvps.add(new BasicNameValuePair("sqm", "1bb5b5b45915c8"));</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//将参数传入post方法中</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;response = httpclient.execute(httpost); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //执行</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;entity = response.getEntity(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //返回服务器响应</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;try{</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("----------------------------------------");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(response.getStatusLine()); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //服务器返回状态</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Header[] headers = response.getAllHeaders(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//返回的HTTP头信息</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (int i=0; i&lt;headers.length; i++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(headers[i]);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("----------------------------------------");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String responseString = null;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (response.getEntity() != null) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;responseString = EntityUtils.toString(response.getEntity()); &nbsp; &nbsp; &nbsp;/ /返回服务器响应的HTML代码</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(responseString); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //打印出服务器响应的HTML代码</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} finally {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (entity != null) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;entity.consumeContent(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // release connection gracefully</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Login form get: " + response.getStatusLine());</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (entity != null) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;entity.consumeContent();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpClient4.0 学习实例 - 页面获取</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">HttpClient 4.0出来不久，所以网络上面相关的实例教程不多，搜httpclient得到的大部分都是基于原 Commons HttpClient 3.1 (legacy) 包的，官网下载页面：http://hc.apache.org/downloads.cgi，如果大家看了官网说明就明白httpclient4.0是从原包分支出来独立成包的，以后原来那个包中的httpclient不会再升级，所以以后我们是用httpclient新分支，由于4.0与之前的3.1包结构以及接口等都有较大变化，所以网上搜到的实例大部分都是不适合4.0的，当然，我们可以通过那些实例去琢磨4.0的用法，我也是新手，记录下学习过程方便以后检索</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">本实例我们来获取抓取网页编码，内容等信息</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">默认情况下，服务器端会根据客户端的请求头信息来返回服务器支持的编码，像google.cn他本身支持utf-8,gb2312等编码，所以如果你在头部中不指定任何头部信息的话他默认会返回gb2312编码，而如果我们在浏览器中直接访问google.cn，通过httplook，或者firefox 的firebug插件查看返回头部信息的话会发现他返回的是UTF-8编码</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">下面我们还是看实例来解说吧，注释等我也放代码里面解释，放完整代码，方便新手理解</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">本实例将</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">使用的httpclient相关包</div>
<div style="font-family: inherit">httpclient-4.0.jar</div>
<div style="font-family: inherit">httpcore-4.0.1.jar</div>
<div style="font-family: inherit">httpmime-4.0.jar</div>
<div style="font-family: inherit">commons-logging-1.0.4.jar等其它相关包</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">// HttpClientTest.java</div>
<div style="font-family: inherit">package com.baihuo.crawler.test;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">import java.util.regex.Matcher;</div>
<div style="font-family: inherit">import java.util.regex.Pattern;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">import org.apache.http.Header;</div>
<div style="font-family: inherit">import org.apache.http.HttpEntity;</div>
<div style="font-family: inherit">import org.apache.http.HttpHost;</div>
<div style="font-family: inherit">import org.apache.http.HttpResponse;</div>
<div style="font-family: inherit">import org.apache.http.client.HttpClient;</div>
<div style="font-family: inherit">import org.apache.http.client.methods.HttpGet;</div>
<div style="font-family: inherit">import org.apache.http.impl.client.DefaultHttpClient;</div>
<div style="font-family: inherit">import org.apache.http.util.EntityUtils;</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">class HttpClientTest {</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;public final static void main(String[] args) throws Exception {</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 初始化，此处构造函数就与3.1中不同</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpHost targetHost = new HttpHost("www.google.cn");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;//HttpGet httpget = new HttpGet("http://www.apache.org/");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpGet httpget = new HttpGet("/");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 查看默认request头部信息</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset"));</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 以下这条如果不加会发现无论你设置Accept-Charset为gbk还是utf-8，他都会默认返回gb2312（本例针对google.cn来说）</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 用逗号分隔显示可以同时接受多种编码</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 验证头部信息设置生效</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset").getValue());</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// Execute HTTP request</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("executing request " + httpget.getURI());</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpResponse response = httpclient.execute(targetHost, httpget);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;//HttpResponse response = httpclient.execute(httpget);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("----------------------------------------");</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Location: " + response.getLastHeader("Location"));</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(response.getStatusLine().getStatusCode());</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(response.getLastHeader("Content-Type"));</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(response.getLastHeader("Content-Length"));</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("----------------------------------------");</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 判断页面返回状态判断是否进行转向抓取新链接</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int statusCode = response.getStatusLine().getStatusCode();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(statusCode == HttpStatus.SC_SEE_OTHER) ||</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 此处重定向处理 &nbsp;此处还未验证</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String newUri = response.getLastHeader("Location").getValue();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;httpget = new HttpGet(newUri);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;response = httpclient.execute(httpget);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// Get hold of the response entity</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;HttpEntity entity = response.getEntity();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// 查看所有返回头部信息</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Header headers[] = response.getAllHeaders();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int ii = 0;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;while (ii &lt; headers.length) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(headers[ii].getName() + ": " + headers[ii].getValue());</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;++ii;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// If the response does not enclose an entity, there is no need</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;// to bother about connection release</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (entity != null) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 将源码流保存在一个byte数组当中，因为可能需要两次用到该流，</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte[] bytes = EntityUtils.toByteArray(entity);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String charSet = "";</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 如果头部Content-Type中包含了编码信息，那么我们可以直接在此处获取</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;charSet = EntityUtils.getContentCharSet(entity);</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("In header: " + charSet);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 如果头部中没有，那么我们需要 查看页面源码，这个方法虽然不能说完全正确，因为有些粗糙的网页编码者没有在页面中写头部编码信息</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (charSet == "") {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;regEx="(?=&lt;meta).*?(?&lt;=charset=[\\'|\\\"]?)([[a-z]|[A-Z]|[0-9]|-]*)";</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;p=Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;m=p.matcher(new String(bytes)); &nbsp;// 默认编码转成字符串，因为我们的匹配中无中文，所以串中可能的乱码对我们没有影响</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result=m.find();</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (m.groupCount() == 1) {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;charSet = m.group(1);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else {</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;charSet = "";</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Last get: " + charSet);</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 至此，我们可以将原byte数组按照正常编码专成字符串输出（如果找到了编码的话）</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Encoding string is: " + new String(bytes, charSet));</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;httpclient.getConnectionManager().shutdown(); &nbsp; &nbsp; &nbsp; &nbsp;</div>
<div style="font-family: inherit">&nbsp;&nbsp; &nbsp;}</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">}</div></div></div><br /><br /><br /><a href="http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html">http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/388609.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:46 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388609.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 教程 (六) </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388608.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:45:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388608.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388608.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388608.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388608.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388608.html</trackback:ping><description><![CDATA[<div id="cnblogs_post_body">
<div style="text-align: left; line-height: normal; font-family: Verdana, Arial, Tahoma, sans-serif; font-size: large; font-weight: bold" class="f3"><span style="font-size: 19px" class="Apple-style-span">第六章 高级主题</span></div>
<div style="padding-bottom: 4px; line-height: normal; padding-left: 0px; padding-right: 0px; font-family: Verdana, Arial, Tahoma, sans-serif; word-wrap: break-word; font-size: 9.5pt; word-break: break-all; padding-top: 4px" class="inherit_c wrap_text">
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">6.1 自定义客户端连接</h3>
<p style="font-family: inherit">在特定条件下，也许需要来定制HTTP报文通过线路传递，越过了可能使用的HTTP参数来处理非标准不兼容行为的方式。比如，对于Web爬虫，它可能需要强制HttpClient接受格式错误的响应头部信息，来抢救报文的内容。</p>
<p style="font-family: inherit">通常插入一个自定义的报文解析器的过程或定制连接实现需要几个步骤：</p>
<p style="font-family: inherit">提供一个自定义LineParser/LineFormatter接口实现。如果需要，实现报文解析/格式化逻辑。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">class MyLineParser extends BasicLineParser {</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public Header parseHeader(</div>
<div style="font-family: inherit">final CharArrayBuffer buffer) throws ParseException {</div>
<div style="font-family: inherit">try {</div>
<div style="font-family: inherit">return super.parseHeader(buffer);</div>
<div style="font-family: inherit">} catch (ParseException ex) {</div>
<div style="font-family: inherit">// 压制ParseException异常</div>
<div style="font-family: inherit">return new BasicHeader("invalid", buffer.toString());</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div></blockquote>
<p style="font-family: inherit">提过一个自定义的OperatedClientConnection实现。替换需要自定义的默认请求/响应解析器，请求/响应格式化器。如果需要，实现不同的报文写入/读取代码。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">class MyClientConnection extends DefaultClientConnection {</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">protected HttpMessageParser createResponseParser(</div>
<div style="font-family: inherit">final SessionInputBuffer buffer,</div>
<div style="font-family: inherit">final HttpResponseFactory responseFactory,</div>
<div style="font-family: inherit">final HttpParams params) {</div>
<div style="font-family: inherit">return new DefaultResponseParser(buffer,</div>
<div style="font-family: inherit">new MyLineParser(),responseFactory,params);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div></blockquote>
<p style="font-family: inherit">为了创建新类的连接，提供一个自定义的ClientConnectionOperator接口实现。如果需要，实现不同的套接字初始化代码。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">class MyClientConnectionOperator extends</div>
<div style="font-family: inherit">DefaultClientConnectionOperator {</div>
<div style="font-family: inherit">public MyClientConnectionOperator(</div>
<div style="font-family: inherit">final SchemeRegistry sr) {</div>
<div style="font-family: inherit">super(sr);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public OperatedClientConnection createConnection() {</div>
<div style="font-family: inherit">return new MyClientConnection();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div></blockquote>
<p style="font-family: inherit">为了创建新类的连接操作，提供自定义的ClientConnectionManager接口实现。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">class MyClientConnManager extends SingleClientConnManager {</div>
<div style="font-family: inherit">public MyClientConnManager(</div>
<div style="font-family: inherit">final HttpParams params,</div>
<div style="font-family: inherit">final SchemeRegistry sr) {</div>
<div style="font-family: inherit">super(params, sr);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">protected ClientConnectionOperator createConnectionOperator(</div>
<div style="font-family: inherit">final SchemeRegistry sr) {</div>
<div style="font-family: inherit">return new MyClientConnectionOperator(sr);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">6.2 有状态的HTTP连接</h3>
<div style="font-family: inherit">HTTP规范假设session状态信息通常是以HTTP cookie格式嵌入在HTTP报文中的，因此HTTP连接通常是无状态的，这个假设在现实生活中通常是不对的。也有一些情况，当HTTP连接使用特定的用户标识或特定的安全上下文来创建时，因此不能和其它用户共享，只能由该用户重用。这样的有状态的HTTP连接的示例就是NTLM认证连接和使用客户端证书认证的SSL连接。</div>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">6.2.1 用户令牌处理器</h4>
<div style="font-family: inherit">HttpClient依赖UserTokenHandler接口来决定给定的执行上下文是否是用户指定的。如果这个上下文是用户指定的或者如果上下文没有包含任何资源或关于当前用户指定详情而是null，令牌对象由这个处理器返回，期望唯一地标识当前的用户。用户令牌将被用来保证用户指定资源不会和其它用户来共享或重用。</div>
<div style="font-family: inherit">
<p style="font-family: inherit">如果它可以从给定的执行上下文中来获得，UserTokenHandler接口的默认实现是使用主类的一个实例来代表HTTP连接的状态对象。UserTokenHandler将会使用基于如NTLM或开启的客户端认证SSL会话认证模式的用户的主连接。如果二者都不可用，那么就不会返回令牌。</p>
<div style="font-family: inherit">如果默认的不能满足它们的需要，用户可以提供一个自定义的实现：</div>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">httpclient.setUserTokenHandler(new UserTokenHandler() {</div>
<div style="font-family: inherit">public Object getUserToken(HttpContext context) {</div>
<div style="font-family: inherit">return context.getAttribute("my-token");</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">});</div></blockquote>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">6.2.2 用户令牌和执行上下文</h4>
<div style="font-family: inherit">在HTTP请求执行的过程中，HttpClient添加了下列和用户标识相关的对象到执行上下文中：</div>
<div style="font-family: inherit">
<p style="font-family: inherit">'http.user-token'：对象实例代表真实的用户标识，通常期望Principle接口的实例。</p>
<div style="font-family: inherit">我们可以在请求被执行后，通过检查本地HTTP上下文的内容，发现是否用于执行请求的连接是有状态的。</div>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">HttpContext localContext = new BasicHttpContext();</div>
<div style="font-family: inherit">HttpGet httpget = new HttpGet("http://localhost:8080/");</div>
<div style="font-family: inherit">HttpResponse response = httpclient.execute(httpget, localContext);</div>
<div style="font-family: inherit">HttpEntity entity = response.getEntity();</div>
<div style="font-family: inherit">if (entity != null) {</div>
<div style="font-family: inherit">entity.consumeContent();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">Object userToken = localContext.getAttribute(ClientContext.USER_TOKEN);</div>
<div style="font-family: inherit">System.out.println(userToken);</div></blockquote>
<h5 style="font-family: Verdana, Arial, Tahoma, sans-serif">6.2.2.1 持久化有状态的连接</h5>
<div style="font-family: inherit">请注意带有状态对象的持久化连接仅当请求被执行时，相同状态对象被绑定到执行上下文时可以被重用。所以，保证相同上下文重用于执行随后的相同用户，或用户令牌绑定到之前请求执行上下文的HTTP请求是很重要的。</div>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">HttpContext localContext1 = new BasicHttpContext();</div>
<div style="font-family: inherit">HttpGet httpget1 = new HttpGet("http://localhost:8080/");</div>
<div style="font-family: inherit">HttpResponse response1 = httpclient.execute(httpget1, localContext1);</div>
<div style="font-family: inherit">HttpEntity entity1 = response1.getEntity();</div>
<div style="font-family: inherit">if (entity1 != null) {</div>
<div style="font-family: inherit">entity1.consumeContent();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">Principal principal = (Principal) localContext1.getAttribute(</div>
<div style="font-family: inherit">ClientContext.USER_TOKEN);</div>
<div style="font-family: inherit">HttpContext localContext2 = new BasicHttpContext();</div>
<div style="font-family: inherit">localContext2.setAttribute(ClientContext.USER_TOKEN, principal);</div>
<div style="font-family: inherit">HttpGet httpget2 = new HttpGet("http://localhost:8080/");</div>
<div style="font-family: inherit">HttpResponse response2 = httpclient.execute(httpget2, localContext2);</div>
<div style="font-family: inherit">HttpEntity entity2 = response2.getEntity();</div>
<div style="font-family: inherit">if (entity2 != null) {</div>
<div style="font-family: inherit">entity2.consumeContent();</div>
<div style="font-family: inherit">}</div></blockquote></div></div></div></div></div><br />转载自：<a href="http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113251.html">http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113251.html</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/388608.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:45 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388608.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 教程 (四) </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388606.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:44:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388606.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388606.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388606.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388606.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388606.html</trackback:ping><description><![CDATA[<div id="cnblogs_post_body">
<div style="text-align: left; line-height: normal; font-family: Verdana, Arial, Tahoma, sans-serif; font-size: large; font-weight: bold" class="f3"><span style="font-size: 19px" class="Apple-style-span">第四章 HTTP认证</span></div>
<div style="padding-bottom: 4px; line-height: normal; padding-left: 0px; padding-right: 0px; font-family: Verdana, Arial, Tahoma, sans-serif; word-wrap: break-word; font-size: 9.5pt; word-break: break-all; padding-top: 4px" class="inherit_c wrap_text">
<div style="font-family: inherit">HttpClient提供对由HTTP标准规范定义的认证模式的完全支持。HttpClient的认证框架可以扩展支持非标准的认证模式，比如NTLM和SPNEGO。</div>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.1 用户凭证</h3>
<p style="font-family: inherit">任何用户身份验证的过程都需要一组可以用于建立用户身份的凭据。用户凭证的最简单的形式可以仅仅是用户名/密码对。UsernamePasswordCredentials代表了一组包含安全规则和明文密码的凭据。这个实现对由HTTP标准规范中定义的标准认证模式是足够的</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pwd");</div>
<div style="font-family: inherit">System.out.println(creds.getUserPrincipal().getName());</div>
<div style="font-family: inherit">System.out.println(creds.getPassword());</div></blockquote>
<p style="font-family: inherit">输出内容为：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">user</div>
<div style="font-family: inherit">pwd</div></blockquote>
<p style="font-family: inherit">NTCredentials是微软Windows指定的实现，它包含了除了用户名/密码对外，一组额外的Windows指定的属性，比如用户域名的名字，比如在微软的Windows网络中，相同的用户使用不同设置的认证可以属于不同的域。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">NTCredentials creds = new NTCredentials("user", "pwd", "workstation", "domain");</div>
<div style="font-family: inherit">System.out.println(creds.getUserPrincipal().getName());</div>
<div style="font-family: inherit">System.out.println(creds.getPassword());</div></blockquote>
<p style="font-family: inherit">输出内容为：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DOMAIN/user</div>
<div style="font-family: inherit">pwd</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.2 认证模式</h3>
<div style="font-family: inherit">AuthScheme接口代表了抽象的，面向挑战-响应的认证模式。一个认证模式期望支持如下的功能：</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">解析和处理由目标服务器在对受保护资源请求的响应中发回的挑战。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">提供处理挑战的属性：认证模式类型和它的参数，如果可用，比如这个认证模型可应用的领域。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">对给定的凭证组和HTTP请求对响应真实认证挑战生成认证字符串。 </li></ul>
<div style="font-family: inherit">要注意认证模式可能是有状态的，涉及一系列的挑战-响应交流。HttpClient附带了一些AuthScheme实现：</div>
<div style="font-family: inherit">
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">Basic（基本）：Basic认证模式定义在RFC 2617中。这个认证模式是不安全的，因为凭据以明文形式传送。尽管它不安全，如果用在和TLS/SSL加密的组合中，Basic认证模式是完全够用的。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">Digest（摘要）：Digest认证模式定义在RFC 2617中。Digest认证模式比Basic有显著的安全提升，对不想通过TLS/SL加密在完全运输安全上开销的应用程序来说也是很好的选择。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">NTLM：NTLM是一个由微软开发的优化Windows平台的专有认证模式。NTLM被认为是比Digest更安全的模式。这个模式需要外部的NTLM引擎来工作。要获取更多详情请参考包含在HttpClient发布包中的NTLM_SUPPORT.txt文档。 </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.3 HTTP认证参数</h3>
<div style="font-family: inherit">有一些可以用于定制HTTP认证过程和独立认证模式行为的参数：</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.protocol.handle-authentication'：定义了是否认证应该被自动处理。这个参数期望的得到一个java.lang.Boolean类型的值。如果这个参数没有被设置，HttpClient将会自动处理认证。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.auth.credential-charset'：定义了当编码用户凭证时使用的字符集。这个参数期望得到一个java.lang.String类型的值。如果这个参数没有被设置，那么就会使用US-ASCII。 </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.4 认证模式注册表</h3>
<div style="font-family: inherit">HttpClient使用AuthSchemeRegistry类维护一个可用的认证模式的注册表。对于每个默认的下面的模式是注册过的：</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">Basic：基本认证模式</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">Digest：摘要认证模式 </li></ul>
<div style="font-family: inherit">请注意NTLM模式没有对每个默认的进行注册。NTLM不能对每个默认开启是应为许可和法律上的原因。要获取更详细的关于如何开启NTLM支持的内容请看这部分。</div>
<div style="font-family: inherit">
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.5 凭据提供器</h3>
<p style="font-family: inherit">凭据提供器意来维护一组用户凭据，还有能够对特定认证范围生产用户凭据。认证范围包括主机名，端口号，领域名称和认证模式名称。当使用凭据提供器来注册凭据时，我们可以提供一个通配符（任意主机，任意端口，任意领域，任意模式）来替代确定的属性值。如果直接匹配没有发现，凭据提供器期望被用来发现最匹配的特定范围。</p>
<div style="font-family: inherit">HttpClient可以和任意实现了CredentialsProvider接口的凭据提供器的物理代表一同工作。默认的CredentialsProvider实现被称为BasicCredentialsProvider，它是简单的凭借java.util.HashMap的实现。</div>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">CredentialsProvider credsProvider = new BasicCredentialsProvider();</div>
<div style="font-family: inherit">credsProvider.setCredentials(</div>
<div style="font-family: inherit">new AuthScope("somehost", AuthScope.ANY_PORT),</div>
<div style="font-family: inherit">new UsernamePasswordCredentials("u1", "p1"));</div>
<div style="font-family: inherit">credsProvider.setCredentials(</div>
<div style="font-family: inherit">new AuthScope("somehost", 8080),</div>
<div style="font-family: inherit">new UsernamePasswordCredentials("u2", "p2"));</div>
<div style="font-family: inherit">credsProvider.setCredentials(</div>
<div style="font-family: inherit">new AuthScope("otherhost", 8080, AuthScope.ANY_REALM, "ntlm"),</div>
<div style="font-family: inherit">new UsernamePasswordCredentials("u3", "p3"));</div>
<div style="font-family: inherit">System.out.println(credsProvider.getCredentials(</div>
<div style="font-family: inherit">new AuthScope("somehost", 80, "realm", "basic")));</div>
<div style="font-family: inherit">System.out.println(credsProvider.getCredentials(</div>
<div style="font-family: inherit">new AuthScope("somehost", 8080, "realm", "basic")));</div>
<div style="font-family: inherit">System.out.println(credsProvider.getCredentials(</div>
<div style="font-family: inherit">new AuthScope("otherhost", 8080, "realm", "basic")));</div>
<div style="font-family: inherit">System.out.println(credsProvider.getCredentials(</div>
<div style="font-family: inherit">new AuthScope("otherhost", 8080, null, "ntlm")));</div></blockquote>
<p style="font-family: inherit">输出内容为：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">[principal: u1]</div>
<div style="font-family: inherit">[principal: u2]</div>
<div style="font-family: inherit">null</div>
<div style="font-family: inherit">[principal: u3]</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.6 HTTP认证和执行上下文</h3>
<p style="font-family: inherit">HttpClient依赖于AuthState类来跟踪关于认证过程状态的详细信息。在HTTP请求执行过程中，HttpClient创建2个AuthState的实例：一个对于目标主机认证，另外一个对于代理认证。如果目标服务器或代理需要用户认证，那么各自的AuthState实例将会被在认证处理过程中使用的AuthScope，AuthScheme和Crednetials来填充。AuthState可以被检查来找出请求的认证是什么类型的，是否匹配AuthScheme的实现，是否凭据提供器对给定的认证范围去找用户凭据。</p>
<p style="font-family: inherit">在HTTP请求执行的过程中，HttpClient添加了下列和认证相关的对象到执行上下文中：</p>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.authscheme-registry'：AuthSchemeRegistry实例代表真实的认证模式注册表。在本地内容中设置的这个属性的值优先于默认的。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.auth.credentials-provider'：CookieSpec实例代表了真实的凭据提供器。在本地内容中设置的这个属性的值优先于默认的。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.auth.target-scope'：AuthState实例代表了真实的目标认证状态。在本地内容中设置的这个属性的值优先于默认的。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.auth.proxy-scope'：AuthState实例代表了真实的代理认证状态。在本地内容中设置的这个属性的值优先于默认的。 </li></ul>
<p style="font-family: inherit">本地的HttpContext对象可以用于定制HTTP认证内容，并先于请求执行或在请求被执行之后检查它的状态：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">HttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">HttpContext localContext = new BasicHttpContext();</div>
<div style="font-family: inherit">HttpGet httpget = new HttpGet("http://localhost:8080/");</div>
<div style="font-family: inherit">HttpResponse response = httpclient.execute(httpget, localContext);</div>
<div style="font-family: inherit">AuthState proxyAuthState = (AuthState) localContext.getAttribute(</div>
<div style="font-family: inherit">ClientContext.PROXY_AUTH_STATE);</div>
<div style="font-family: inherit">System.out.println("Proxy auth scope: " + proxyAuthState.getAuthScope());</div>
<div style="font-family: inherit">System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());</div>
<div style="font-family: inherit">System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());</div>
<div style="font-family: inherit">AuthState targetAuthState = (AuthState) localContext.getAttribute(</div>
<div style="font-family: inherit">ClientContext.TARGET_AUTH_STATE);</div>
<div style="font-family: inherit">System.out.println("Target auth scope: " + targetAuthState.getAuthScope());</div>
<div style="font-family: inherit">System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());</div>
<div style="font-family: inherit">System.out.println("Target auth credentials: " + targetAuthState.getCredentials());</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.7 抢占认证</h3>
<p style="font-family: inherit">HttpClient不支持开箱的抢占认证，因为滥用或重用不正确的抢占认证可能会导致严重的安全问题，比如将用户凭据以明文形式发送给未认证的第三方。因此，用户期望评估抢占认证和在它们只能应用程序环境内容安全风险潜在的好处，而且要求使用如协议拦截器的标准HttpClient扩展机制添加对抢占认证的支持。</p>
<p style="font-family: inherit">这是一个简单的协议拦截器，如果没有企图认证，来抢先引入BasicScheme的实例到执行上下文中。请注意拦截器必须在标准认证拦截器之前加入到协议处理链中。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {</div>
<div style="font-family: inherit">public void process(final HttpRequest request,</div>
<div style="font-family: inherit">final HttpContext context) throws HttpException, IOException {</div>
<div style="font-family: inherit">AuthState authState = (AuthState) context.getAttribute(</div>
<div style="font-family: inherit">ClientContext.TARGET_AUTH_STATE);</div>
<div style="font-family: inherit">CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);</div>
<div style="font-family: inherit">HttpHost targetHost = (HttpHost) context.getAttribute(</div>
<div style="font-family: inherit">ExecutionContext.HTTP_TARGET_HOST);</div>
<div style="font-family: inherit">// 如果没有初始化auth模式</div>
<div style="font-family: inherit">if (authState.getAuthScheme() == null) {</div>
<div style="font-family: inherit">AuthScope authScope = new AuthScope(</div>
<div style="font-family: inherit">targetHost.getHostName(),</div>
<div style="font-family: inherit">targetHost.getPort());</div>
<div style="font-family: inherit">// 获得匹配目标主机的凭据</div>
<div style="font-family: inherit">Credentials creds = credsProvider.getCredentials(authScope);</div>
<div style="font-family: inherit">// 如果发现了，抢先生成BasicScheme</div>
<div style="font-family: inherit">if (creds != null) {</div>
<div style="font-family: inherit">authState.setAuthScheme(new BasicScheme());</div>
<div style="font-family: inherit">authState.setCredentials(creds);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">};</div>
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">// 作为第一个拦截器加入到协议链中</div>
<div style="font-family: inherit">httpclient.addRequestInterceptor(preemptiveAuth, 0);</div></blockquote></div></div>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.8 NTLM 认证</h3>
<p style="font-family: inherit">当前HttpClient没有提对开箱的NTLM认证模式的支持也可能永远也不会。这个原因是法律上的而不是技术上的。然而，NTLM认证可以使用外部的NTLM引擎比如JCIFS[http://jcifs.samba.org/]来开启，类库由Samba[http://www.samba.org/]项目开发，作为它们Windows的交互操作程序套装的一部分。要获取详细内容请参考HttpClient发行包中包含的NTLM_SUPPORT.txt文档。</p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">4.8.1 NTLM连接持久化</h4>
<p style="font-family: inherit">NTLM认证模式是在计算开销方面昂贵的多的，而且对标准的Basic和Digest模式的性能影响也很大。这很可能是为什么微软选择NTLM认证模式为有状态的主要原因之一。也就是说，一旦认证通过，用户标识是和连接的整个生命周期相关联的。NTLM连接的状态特性使得连接持久化非常复杂，对于明显的原因，持久化NTLM连接不能被使用不同用户标识的用户重用。标准的连接管理器附带HttpClient是完全能够管理状态连接的。而逻辑相关的，使用同一session和执行上下文为了让它们了解到当前的用户标识的请求也是极为重要的。否则，HttpClient将会终止对每个基于NTLM保护资源的HTTP请求创建新的HTTP连接。要获取关于有状态的HTTP连接的详细讨论，请参考这个部分。</p>
<p style="font-family: inherit">因为NTLM连接是有状态的，通常建议使用相对简单的方法触发NTLM认证，比如GET或HEAD，而重用相同的连接来执行代价更大的方法，特别是它们包含请求实体，比如POST或PUT。</p>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">NTCredentials creds = new NTCredentials("user", "pwd", "myworkstation", "microsoft.com");</div>
<div style="font-family: inherit">httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);</div>
<div style="font-family: inherit">HttpHost target = new HttpHost("www.microsoft.com", 80, "http");</div>
<div style="font-family: inherit">// 保证相同的内容来用于执行逻辑相关的请求</div>
<div style="font-family: inherit">HttpContext localContext = new BasicHttpContext();</div>
<div style="font-family: inherit">// 首先执行简便的方法。这会触发NTLM认证</div>
<div style="font-family: inherit">HttpGet httpget = new HttpGet("/ntlm-protected/info");</div>
<div style="font-family: inherit">HttpResponse response1 = httpclient.execute(target, httpget, localContext);</div>
<div style="font-family: inherit">HttpEntity entity1 = response1.getEntity();</div>
<div style="font-family: inherit">if (entity1 != null) {</div>
<div style="font-family: inherit">entity1.consumeContent();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">//之后使用相同的内容（和连接）执行开销大的方法。</div>
<div style="font-family: inherit">HttpPost httppost = new HttpPost("/ntlm-protected/form");</div>
<div style="font-family: inherit">httppost.setEntity(new StringEntity("lots and lots of data"));</div>
<div style="font-family: inherit">HttpResponse response2 = httpclient.execute(target, httppost, localContext);</div>
<div style="font-family: inherit">HttpEntity entity2 = response2.getEntity();</div>
<div style="font-family: inherit">if (entity2 != null) {</div>
<div style="font-family: inherit">entity2.consumeContent();</div>
<div style="font-family: inherit">}</div></blockquote></div>
<p style="font-family: inherit">&nbsp;</p></div></div><br /><br />转载自：<a href="http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113247.html">http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113247.html</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/388606.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:44 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388606.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 教程 (五) </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388607.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:44:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388607.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388607.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388607.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388607.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388607.html</trackback:ping><description><![CDATA[<div id="cnblogs_post_body">
<div style="border-bottom: #bbbbbb 1px solid; border-left: #bbbbbb 1px solid; padding-bottom: 8px; background-color: #fffffa; padding-left: 8px; padding-right: 8px; font-family: Verdana, Arial, Tahoma, sans-serif; border-top: #bbbbbb 1px solid; border-right: #bbbbbb 1px solid; padding-top: 8px; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial" class="newspager_template">
<div style="text-align: left; line-height: normal; font-family: Verdana, Arial, Tahoma, sans-serif; font-size: large; font-weight: bold" class="f3"><span style="font-size: 19px" class="Apple-style-span">第五章 HTTP客户端服务</span></div>
<div style="padding-bottom: 4px; line-height: normal; padding-left: 0px; padding-right: 0px; font-family: Verdana, Arial, Tahoma, sans-serif; word-wrap: break-word; font-size: 9.5pt; word-break: break-all; padding-top: 4px" class="inherit_c wrap_text">
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">5.1 HttpClient门面</h3>
<p style="font-family: inherit">HttpClient接口代表了最重要的HTTP请求执行的契约。它没有在请求执行处理上强加限制或特殊细节，而在连接管理，状态管理，认证和处理重定向到具体实现上留下了细节。这应该使得很容易使用额外的功能，比如响应内容缓存来装饰接口。</p>
<p style="font-family: inherit">DefaultHttpClient是HttpClient接口的默认实现。这个类扮演了很多特殊用户程序或策略接口实现负责处理特定HTTP协议方面，比如重定向到处理认证或做出关于连接持久化和保持活动的持续时间决定的门面。这使得用户可以选择使用定制，具体程序等来替换某些方面默认实现。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">httpclient.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public long getKeepAliveDuration(HttpResponse response,</div>
<div style="font-family: inherit">HttpContext context) {</div>
<div style="font-family: inherit">long keepAlive = super.getKeepAliveDuration(response, context);</div>
<div style="font-family: inherit">if (keepAlive == -1) {</div>
<div style="font-family: inherit">// 如果keep-alive值没有由服务器明确设置，那么保持连接持续5秒。</div>
<div style="font-family: inherit">keepAlive = 5000;</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">return keepAlive;</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">});</div></blockquote>
<p style="font-family: inherit">DefaultHttpClient也维护一组协议拦截器，意在处理即将离开的请求和即将到达的响应，而且提供管理那些拦截器的方法。新的协议拦截器可以被引入到协议处理器链中，或在需要时从中移除。内部的协议拦截器存储在一个简单的java.util.ArrayList中。它们以被加入到list中的自然顺序来执行。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">httpclient.removeRequestInterceptorByClass(RequestUserAgent.class);</div>
<div style="font-family: inherit">httpclient.addRequestInterceptor(new HttpRequestInterceptor() {</div>
<div style="font-family: inherit">public void process(</div>
<div style="font-family: inherit">HttpRequest request, HttpContext context)</div>
<div style="font-family: inherit">throws HttpException, IOException {</div>
<div style="font-family: inherit">request.setHeader(HTTP.USER_AGENT, "My-own-client");</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">});</div></blockquote>
<p style="font-family: inherit">DefaultHttpClient是线程安全的。建议相同的这个类的实例被重用于多个请求的执行。当一个DefaultHttpClient实例不再需要而且要脱离范围时，和它关联的连接管理器必须调用ClientConnectionManager#shutdown()方法关闭。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">HttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">// 做些有用的事</div>
<div style="font-family: inherit">httpclient.getConnectionManager().shutdown();</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">5.2 HttpClient参数</h3>
<div style="font-family: inherit">这些是可以用于定制默认HttpClient实现行为的参数：</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.protocol.handle-redirects'：定义了重定向是否应该自动处理。这个参数期望得到一个java.lang.Boolean类型的值。如果这个参数没有被设置，HttpClient将会自动处理重定向。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.protocol.reject-relative-redirect'：定义了是否相对的重定向应该被拒绝。HTTP规范需要位置值是一个绝对URI。这个参数期望得到一个java.lang.Boolean类型的值。如果这个参数没有被设置，那么就允许相对重定向。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.protocol.max-redirects'：定义了要遵循重定向的最大数量。这个重定向数字的限制意在防止由破碎的服务器端脚本引发的死循环。这个参数期望得到一个java.lang.Integer类型的值。如果这个参数没有被设置，那么只允许不多余100次重定向。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.protocol.allow-circular-redirects'：定义环形重定向（重定向到相同路径）是否被允许。HTTP规范在环形重定向没有足够清晰的允许表述，因此这作为可选的是可以开启的。这个参数期望得到一个java.lang.Boolean类型的值。如果这个参数没有被设置，那么环形重定向就不允许。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.connection-manager.factory-class-name'：定义了默认的ClientConnectionManager实现的类型。这个参数期望得到一个java.lang.String类型的值。如果这个参数没有被设置，对于每个默认的将使用SingleClientConnManager。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.virtual-host'：定义了在头部信息Host中使用的虚拟主机名称，来代替物理主机名称。这个参数期望得到一个HttpHost类型的值。如果这个参数没有被设置，那么将会使用目标主机的名称或IP地址。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.default-headers'：定义了每次请求默认发送的头部信息。这个参数期望得到一个包含Header对象的java.util.Collection类型值。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.default-host'：定义了默认主机。如果目标主机没有在请求URI（相对URI）中明确指定，那么就使用默认值。这个参数期望得到一个HttpHost类型的值。 </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">5.3 自动重定向处理</h3>
<p style="font-family: inherit">HttpClient处理所有类型的自动重定向，除了那些由HTTP规范明令禁止的，比如需要用户干预的。参考其它（状态码303）POST和PUT请求重定向转换为由HTTP规范需要的GET请求。</p>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">5.4 HTTP客户端和执行上下文</h3>
<p style="font-family: inherit">DefaultHttpClient将HTTP请求视为不变的对象，也从来不会假定在请求执行期间改变。相反，它创建了一个原请求对象私有的可变副本，副本的属性可以基于执行上下文来更新。因此，如目标主键和请求URI的final类型的请求参数可以在请求执行之后，由检查本地HTTP上下文来决定。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">HttpContext localContext = new BasicHttpContext();</div>
<div style="font-family: inherit">HttpGet httpget = new HttpGet("http://localhost:8080/");</div>
<div style="font-family: inherit">HttpResponse response = httpclient.execute(httpget, localContext);</div>
<div style="font-family: inherit">HttpHost target = (HttpHost) localContext.getAttribute(</div>
<div style="font-family: inherit">ExecutionContext.HTTP_TARGET_HOST);</div>
<div style="font-family: inherit">HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(</div>
<div style="font-family: inherit">ExecutionContext.HTTP_REQUEST);</div>
<div style="font-family: inherit">System.out.println("Target host: " + target);</div>
<div style="font-family: inherit">System.out.println("Final request URI: " + req.getURI());</div>
<div style="font-family: inherit">System.out.println("Final request method: " + req.getMethod());</div></blockquote></div></div></div>
<div id="MySignature"></div>
<div id="blog_post_info_block">
<div id="blog_post_info"><a href="http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113249.html">http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113249.html</a></div></div><img src ="http://www.blogjava.net/stevenjohn/aggbug/388607.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:44 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388607.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 教程 (三) </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388605.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:43:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388605.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388605.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388605.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388605.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388605.html</trackback:ping><description><![CDATA[<font size="5">第三章 HTTP状态管理</font> 
<div style="padding-bottom: 4px; line-height: normal; padding-left: 0px; padding-right: 0px; font-family: Verdana, Arial, Tahoma, sans-serif; word-wrap: break-word; font-size: 9.5pt; word-break: break-all; padding-top: 4px" class="inherit_c wrap_text">
<p style="font-family: inherit"><span style="color: #000000">原始的HTTP是被设计为无状态的，面向请求/响应的协议，没有特殊规定有状态的，贯穿一些逻辑相关的请求/响应交换的会话。由于HTTP协议变得越来越普及和受欢迎，越来越多的从前没有打算使用它的系统也开始为应用程序来使用它，比如作为电子商务应用程序的传输方式。因此，支持状态管理就变得非常必要了。</span></p>
<p style="font-family: inherit"><span style="color: #000000">网景公司，一度成为Web客户端和服务器软件开发者的领导方向，在它们基于专有规范的产品中实现了对HTTP状态管理的支持。之后，网景公司试图通过发布规范草案来规范这种机制。它们的努力通过RFC标准跟踪促成了这些规范定义。然而，在很多应用程序中的状态管理仍然基于网景公司的草案而不兼容官方的规范。很多主要的Web浏览器开发者觉得有必要保留那些极大促进标准片段应用程序的兼容性。</span></p>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.1 HTTP cookies</span></h3>
<p style="font-family: inherit"><span style="color: #000000">Cookie是HTTP代理和目标服务器可以交流保持会话的状态信息的令牌或短包。网景公司的工程师用它来指&#8220;魔法小甜饼&#8221;和粘住的名字。</span></p>
<p style="font-family: inherit"><span style="color: #000000">HttpClient使用Cookie接口来代表抽象的cookie令牌。在它的简单形式中HTTP的cookie几乎是名/值对。通常一个HTTP的cookie也包含一些属性，比如版本号，合法的域名，指定cookie应用所在的源服务器URL子集的路径，cookie的最长有效时间。</span></p>
<p style="font-family: inherit"><span style="color: #000000">SetCookie接口代表由源服务器发送给HTTP代理的响应中的头部信息Set-Cookie来维持一个对话状态。SetCookie2接口和指定的Set-Cookie2方法扩展了SetCookie。</span></p>
<p style="font-family: inherit"><span style="color: #000000">SetCookie接口和额外的如获取原始cookie属性的能力，就像它们由源服务器指定的客户端特定功能扩展了Cookie接口。这对生成Cookie头部很重要，因为一些cookie规范需要。Cookie头部应该包含在Set-Cookie或Set-Cookie2头部中指定的特定属性。</span></p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.1.1 Cookie版本</span></h4>
<div style="font-family: inherit"><span style="color: #000000">Cookie兼容网景公司的草案标准，但是版本0被认为是不符合官方规范的。符合标准的cookie的期望版本是1。HttpClient可以处理基于不同版本的cookie。</span></div>
<p style="font-family: inherit"><span style="color: #000000">这里有一个重新创建网景公司草案cookie示例：</span></p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">BasicClientCookie netscapeCookie = new BasicClientCookie("name", "value");</span></div>
<div style="font-family: inherit"><span style="color: #000000">netscapeCookie.setVersion(0);</span></div>
<div style="font-family: inherit"><span style="color: #000000">netscapeCookie.setDomain(".mycompany.com");</span></div>
<div style="font-family: inherit"><span style="color: #000000">netscapeCookie.setPath("/");</span></div></blockquote>
<p style="font-family: inherit"><span style="color: #000000">这是一个重新创建标准cookie的示例。要注意符合标准的cookie必须保留由源服务器发送的所有属性：</span></p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">BasicClientCookie stdCookie = new BasicClientCookie("name", "value");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setVersion(1);</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setDomain(".mycompany.com");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setPath("/");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setSecure(true);</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 精确设置由服务器发送的属性</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com");</span></div></blockquote>
<p style="font-family: inherit"><span style="color: #000000">这是一个重新创建Set-Cookie2兼容cookie的实例。要注意符合标准的cookie必须保留由源服务器发送的所有属性：</span></p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">BasicClientCookie2 stdCookie = new BasicClientCookie2("name", "value");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setVersion(1);</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setDomain(".mycompany.com");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setPorts(new int[] {80,8080});</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setPath("/");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setSecure(true);</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 精确设置由服务器发送的属性</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com");</span></div>
<div style="font-family: inherit"><span style="color: #000000">stdCookie.setAttribute(ClientCookie.PORT_ATTR, "80,8080");</span></div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.2 Cookie规范</span></h3>
<div style="font-family: inherit"><span style="color: #000000">CookieSpec接口代表了cookie管理的规范。Cookie管理规范希望如下几点：</span></div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">解析的Set-Cookie规则还有可选的Set-Cookie2头部信息。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">验证解析cookie的规则。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">格式化给定主机的Cookie头部信息，原始端口和路径。</span> </li></ul>
<p style="font-family: inherit"><span style="color: #000000">HttpClient附带了一些CookieSpec的实现：</span></p>
<ul style="padding-right: 40px; font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">网景公司草案：这个规范符合由网景通讯发布的原始草案规范。应当避免，除非有绝对的必要去兼容遗留代码。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">RFC 2109：官方HTTP状态管理规范并取代的老版本，被RFC 2965取代。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">RFC 2965：官方HTTP状态管理规范。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">浏览器兼容性：这个实现努力去密切模仿（mis）通用Web浏览器应用程序的实现。比如微软的Internet Explorer和Mozilla的FireFox浏览器。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">最佳匹配：&#8217;Meta&#8217;（元）cookie规范采用了一些基于又HTTP响应发送的cookie格式的cookie策略。它基本上聚合了以上所有的实现到以一个类中。</span> </li></ul>
<div style="font-family: inherit"><span style="color: #000000">强烈建议使用Best Match策略，让HttpClient在运行时基于执行上下文采用一些合适的兼容等级。</span></div>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.3 HTTP cookie和状态管理参数</span></h3>
<div style="font-family: inherit"><span style="color: #000000">这些是用于定制HTTP状态管理和独立的cookie规范行为的参数。</span></div>
<div style="font-family: inherit">
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.protocol.cookie-datepatterns'：定义了用于解析非标准的expires属性的合法日期格式。只是对兼容不符合规定的，仍然使用网景公司草案定义的expires而不使用标准的max-age属性服务器需要。这个参数期望得到一个java.util.Collection类型的值。集合元素必须是java.lang.String类型，来兼容java.text.SimpleDateFormat的语法。如果这个参数没有被设置，那么默认的选择就是CookieSpec实现规范的值。要注意这个参数的应用。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.protocol.single-cookie-header'：定义了是否cookie应该强制到一个独立的Cookie请求头部信息中。否则，每个cookie就被当作分离的Cookie头部信息来格式化。这个参数期望得到一个java.lang.Boolean类型的值。如果这个参数没有被设置，那么默认的选择就是CookieSpec实现规范的值。要注意这个参数仅仅严格应用于cookie规范（RFC 2109和RFC 2965）。浏览器兼容性和网景公司草案策略将会放置所有的cookie到一个请求头部信息中。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.protocol.cookie-policy'：定义了用于HTTP状态管理的cookie规范的名字。这个参数期望得到一个java.lang.String类型的值。如果这个参数没有被设置，那么合法的日期格式就是CookieSpec实现规范的值。</span> </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.4 Cookie规范注册表</span></h3>
<div style="font-family: inherit"><span style="color: #000000">HttpClient使用CookieSpecRegistry类维护一个可用的cookie规范注册表。下面的规范对于每个默认都是注册过的：</span></div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">兼容性：浏览器兼容性（宽松策略）。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">网景：网景公司草案。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">rfc2109：RFC 2109（过时的严格策略）。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">rfc2965：RFC 2965（严格策略的标准符合）。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">best-match：最佳匹配meta（元）策略。</span> </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.5 选择cookie策略</span></h3>
<div style="font-family: inherit"><span style="color: #000000">Cookie策略可以在HTTP客户端被设置，如果需要，在HTTP请求级重写。</span></div>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">HttpClient httpclient = new DefaultHttpClient();</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 对每个默认的强制严格cookie策略</span></div>
<div style="font-family: inherit"><span style="color: #000000">httpclient.getParams().setParameter(</span></div>
<div style="font-family: inherit"><span style="color: #000000">ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpGet httpget = new HttpGet("http://www.broken-server.com/");</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 对这个请求覆盖默认策略</span></div>
<div style="font-family: inherit"><span style="color: #000000">httpget.getParams().setParameter(</span></div>
<div style="font-family: inherit"><span style="color: #000000">ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);</span></div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.6 定制cookie策略</span></h3>
<div style="font-family: inherit"><span style="color: #000000">为了实现定制cookie策略，我们应该创建CookieSpec接口的定制实现类，创建一个CookieSpecFactory实现来创建和初始化定制实现的实例并和HttpClient注册这个工厂。一旦定制实现被注册了，它可以和标准的cookie实现有相同的活性。</span></div>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">CookieSpecFactory csf = new CookieSpecFactory() {</span></div>
<div style="font-family: inherit"><span style="color: #000000">public CookieSpec newInstance(HttpParams params) {</span></div>
<div style="font-family: inherit"><span style="color: #000000">return new BrowserCompatSpec() {</span></div>
<div style="font-family: inherit"><span style="color: #000000">@Override</span></div>
<div style="font-family: inherit"><span style="color: #000000">public void validate(Cookie cookie, CookieOrigin origin)</span></div>
<div style="font-family: inherit"><span style="color: #000000">throws MalformedCookieException {</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 这相当简单</span></div>
<div style="font-family: inherit"><span style="color: #000000">}</span></div>
<div style="font-family: inherit"><span style="color: #000000">};</span></div>
<div style="font-family: inherit"><span style="color: #000000">}</span></div>
<div style="font-family: inherit"><span style="color: #000000">};</span></div>
<div style="font-family: inherit"><span style="color: #000000">DefaultHttpClient httpclient = new DefaultHttpClient();</span></div>
<div style="font-family: inherit"><span style="color: #000000">httpclient.getCookieSpecs().register("easy", csf);</span></div>
<div style="font-family: inherit"><span style="color: #000000">httpclient.getParams().setParameter(</span></div>
<div style="font-family: inherit"><span style="color: #000000">ClientPNames.COOKIE_POLICY, "easy");</span></div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.7 Cookie持久化</span></h3>
<div style="font-family: inherit"><span style="color: #000000">HttpClient可以和任意物理表示的实现了CookieStore接口的持久化cookie存储一起使用。默认的CookieStore实现称为BasicClientCookie，这是凭借java.util.ArrayList的一个简单实现。在BasicClientCookie对象中存储的cookie当容器对象被垃圾回收机制回收时会丢失。如果需要，用户可以提供更复杂的实现。</span></div>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">DefaultHttpClient httpclient = new DefaultHttpClient();</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 创建一个本地的cookie store实例</span></div>
<div style="font-family: inherit"><span style="color: #000000">CookieStore cookieStore = new MyCookieStore();</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 如果需要填充cookie</span></div>
<div style="font-family: inherit"><span style="color: #000000">BasicClientCookie cookie = new BasicClientCookie("name", "value");</span></div>
<div style="font-family: inherit"><span style="color: #000000">cookie.setVersion(0);</span></div>
<div style="font-family: inherit"><span style="color: #000000">cookie.setDomain(".mycompany.com");</span></div>
<div style="font-family: inherit"><span style="color: #000000">cookie.setPath("/");</span></div>
<div style="font-family: inherit"><span style="color: #000000">cookieStore.addCookie(cookie);</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 设置存储</span></div>
<div style="font-family: inherit"><span style="color: #000000">httpclient.setCookieStore(cookieStore);</span></div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.8 HTTP状态管理和执行上下文</span></h3>
<div style="font-family: inherit"><span style="color: #000000">在HTTP请求执行的过程中，HttpClient添加了下列和状态管理相关的对象到执行上下文中：</span></div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.cookiespec-registry'：CookieSpecRegistry实例代表了实际的cookie规范注册表。这个属性的值设置在本地内容中，优先于默认的。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.cookie-spec'：CookieSpec实例代表真实的cookie规范。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.cookie-origin'：CookieOrigin实例代表了真实的源服务器的详细信息。</span></li><li style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #888888">'http.cookie-store'：CookieStore实例代表了真实的cookie存储。设置在本地内容中的这个属性的值优先于默认的。</span> </li></ul>
<p style="font-family: inherit"><span style="color: #000000">本地的HttpContext对象可以被用来定制HTTP状态管理内容，先于请求执行或在请求执行之后检查它的状态：</span></p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">HttpClient httpclient = new DefaultHttpClient();</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpContext localContext = new BasicHttpContext();</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpGet httpget = new HttpGet("http://localhost:8080/");</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpResponse response = httpclient.execute(httpget, localContext);</span></div>
<div style="font-family: inherit"><span style="color: #000000">CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute(</span></div>
<div style="font-family: inherit"><span style="color: #000000">ClientContext.COOKIE_ORIGIN);</span></div>
<div style="font-family: inherit"><span style="color: #000000">System.out.println("Cookie origin: " + cookieOrigin);</span></div>
<div style="font-family: inherit"><span style="color: #000000">CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute(</span></div>
<div style="font-family: inherit"><span style="color: #000000">ClientContext.COOKIE_SPEC);</span></div>
<div style="font-family: inherit"><span style="color: #000000">System.out.println("Cookie spec used: " + cookieSpec);</span></div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif"><span style="color: #000000">3.9 每个用户/线程的状态管理</span></h3>
<div style="font-family: inherit"><span style="color: #000000">我们可以使用独立的本地执行上下文来实现对每个用户（或每个线程）状态的管理。定义在本地内容中的cookie规范注册表和cookie存储将会优先于设置在HTTP客户端级别中默认的那些。</span></div>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit"><span style="color: #000000">HttpClient httpclient = new DefaultHttpClient();</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 创建cookie store的本地实例</span></div>
<div style="font-family: inherit"><span style="color: #000000">CookieStore cookieStore = new BasicCookieStore();</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 创建本地的HTTP内容</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpContext localContext = new BasicHttpContext();</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 绑定定制的cookie store到本地内容中</span></div>
<div style="font-family: inherit"><span style="color: #000000">localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpGet httpget = new HttpGet("http://www.google.com/");</span></div>
<div style="font-family: inherit"><span style="color: #000000">// 作为参数传递本地内容</span></div>
<div style="font-family: inherit"><span style="color: #000000">HttpResponse response = httpclient.execute(httpget, localContext)</span></div></blockquote></div></div></div></div></div></div><br /><br /><br /><a href="http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113246.html">http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113246.html</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/388605.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:43 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388605.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 教程 (二) </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388604.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:42:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388604.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388604.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388604.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388604.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388604.html</trackback:ping><description><![CDATA[<div style="text-align: left; line-height: normal; font-family: Verdana, Arial, Tahoma, sans-serif; font-size: large; font-weight: bold" class="f3">
<div style="text-align: left; line-height: normal; font-family: Verdana, Arial, Tahoma, sans-serif; color: #333333; font-size: large; font-weight: bold" class="f3"><span style="font-size: 19px" class="Apple-style-span">第二章 连接管理</span></div>
<div style="padding-bottom: 4px; line-height: normal; padding-left: 0px; padding-right: 0px; font-family: Verdana, Arial, Tahoma, sans-serif; word-wrap: break-word; color: #333333; font-size: 9.5pt; word-break: break-all; padding-top: 4px" class="inherit_c wrap_text">
<p style="font-family: inherit">HttpClient有一个对连接初始化和终止，还有在活动连接上I/O操作的完整控制。而连接操作的很多方面可以使用一些参数来控制。</p>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.1 连接参数</h3>
<p style="font-family: inherit">这些参数可以影响连接操作：</p>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.socket.timeout'：定义了套接字的毫秒级超时时间（SO_TIMEOUT），这就是等待数据，换句话说，在两个连续的数据包之间最大的闲置时间。如果超时时间是0就解释为是一个无限大的超时时间。这个参数期望得到一个java.lang.Integer类型的值。如果这个参数没有被设置，那么读取操作就不会超时（无限大的超时时间）。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.tcp.nodelay'：决定了是否使用Nagle算法。Nagle算法视图通过最小化发送的分组数量来节省带宽。当应用程序希望降低网络延迟并提高性能时，它们可以关闭Nagle算法（也就是开启TCP_NODELAY）。数据将会更早发送，增加了带宽消耗的成文。这个参数期望得到一个java.lang.Boolean类型的值。如果这个参数没有被设置，那么TCP_NODELAY就会开启（无延迟）。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.socket.buffer-size'：决定了内部套接字缓冲使用的大小，来缓冲数据同时接收/传输HTTP报文。这个参数期望得到一个java.lang.Integer类型的值。如果这个参数没有被设置，那么HttpClient将会分配8192字节的套接字缓存。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.socket.linger'：使用指定的秒数拖延时间来设置SO_LINGER。最大的连接超时值是平台指定的。值0暗示了这个选项是关闭的。值-1暗示了使用了JRE默认的。这个设置仅仅影响套接字关闭操作。如果这个参数没有被设置，那么就假设值为-1（JRE默认）。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.connection.timeout'：决定了直到连接建立时的毫秒级超时时间。超时时间的值为0解释为一个无限大的时间。这个参数期望得到一个java.lang.Integer类型的值。如果这个参数没有被设置，连接操作将不会超时（无限大的超时时间）。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.connection.stalecheck'：决定了是否使用旧的连接检查。当在一个连接之上执行一个请求而服务器端的连接已经关闭时，关闭旧的连接检查可能导致在获得一个I/O错误风险时显著的性能提升（对于每一个请求，检查时间可以达到30毫秒）。这个参数期望得到一个java.lang.Boolean类型的值。出于性能的关键操作，检查应该被关闭。如果这个参数没有被设置，那么旧的连接将会在每个请求执行之前执行。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.connection.max-line-length'：决定了最大请求行长度的限制。如果设置为一个正数，任何HTTP请求行超过这个限制将会引发java.io.IOException异常。负数或零将会关闭这个检查。这个参数期望得到一个java.lang.Integer类型的值。如果这个参数没有被设置，那么就不强制进行限制了。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.connection.max-header-count'：决定了允许的最大HTTP头部信息数量。如果设置为一个正数，从数据流中获得的HTTP头部信息数量超过这个限制就会引发java.io.IOException异常。负数或零将会关闭这个检查。这个参数期望得到一个java.lang.Integer类型的值。如果这个参数没有被设置，那么就不</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">强制进行限制了。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.connection.max-status-line-garbage'：决定了在期望得到HTTP响应状态行之前可忽略请求行的最大数量。使用HTTP/1.1持久性连接，这个问题产生的破碎的脚本将会返回一个错误的Content-Length（有比指定的字节更多的发送）。不幸的是，在某些情况下，这个不能在错误响应后来侦测，只能在下一次之前。所以HttpClient必须以这种方式跳过那些多余的行。这个参数期望得到一个java.lang.Integer类型的值。0是不允许在状态行之前的所有垃圾/空行。使用java.lang.Integer#MAX_VALUE来设置不限制的数字。如果这个参数没有被设置那就假设是不限制的。 </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.2 持久连接</h3>
<p style="font-family: inherit">从一个主机向另外一个建立连接的过程是相当复杂的，而且包含了两个终端之间的很多包的交换，它是相当费时的。连接握手的开销是很重要的，特别是对小量的HTTP报文。如果打开的连接可以被重用来执行多次请求，那么就可以达到很高的数据吞吐量。</p>
<p style="font-family: inherit">HTTP/1.1强调HTTP连接默认情况可以被重用于多次请求。HTTP/1.0兼容的终端也可以使用相似的机制来明确地交流它们的偏好来保证连接处于活动状态，也使用它来处理多个请求。HTTP代理也可以保持空闲连接处于一段时间的活动状态，防止对相同目标主机的一个连接也许对随后的请求需要。保持连接活动的能力通常被称作持久性连接。HttpClient完全支持持久性连接。</p>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.3 HTTP连接路由</h3>
<p style="font-family: inherit">HttpClient能够直接或通过路由建立连接到目标主机，这会涉及多个中间连接，也被称为跳。HttpClient区分路由和普通连接，通道和分层。通道连接到目标主机的多个中间代理的使用也称作是代理链。</p>
<p style="font-family: inherit">普通路由由连接到目标或仅第一次的代理来创建。通道路由通过代理链到目标连接到第一通道来建立。没有代理的路由不是通道的，分层路由通过已存在连接的分层协议来建立。协议仅仅可以在到目标的通道上或在没有代理的直接连接上分层。</p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.3.1 路由计算</h4>
<p style="font-family: inherit">RouteInfo接口代表关于最终涉及一个或多个中间步骤或跳的目标主机路由的信息。HttpRoute是RouteInfo的具体实现，这是不能改变的（是不变的）。HttpTracker是可变的RouteInfo实现，由HttpClient在内部使用来跟踪到最大路由目标的剩余跳数。HttpTracker可以在成功执行向路由目标的下一跳之后更新。HttpRouteDirector是一个帮助类，可以用来计算路由中的下一跳。这个类由HttpClient在内部使用。</p>
<p style="font-family: inherit">HttpRoutePlanner是一个代表计算到基于执行上下文到给定目标完整路由策略的接口。HttpClient附带两个默认的HttpRoutePlanner实现。ProxySelectorRoutePlanner是基于java.net.ProxySelector的。默认情况下，它会从系统属性中或从运行应用程序的浏览器中选取JVM的代理设置。DefaultHttpRoutePlanner实现既不使用任何Java系统属性，也不使用系统或浏览器的代理设置。它只基于HTTP如下面描述的参数计算路由。</p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.3.2 安全HTTP连接</h4>
<p style="font-family: inherit">如果信息在两个不能由非认证的第三方进行读取或修改的终端之间传输，HTTP连接可以被认为是安全的。SSL/TLS协议是用来保证HTTP传输安全使用最广泛的技术。而其它加密技术也可以被使用。通常来说，HTTP传输是在SSL/TLS加密连接之上分层的。</p>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.4 HTTP路由参数</h3>
<div style="font-family: inherit">这些参数可以影响路由计算：</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.route.default-proxy'：定义可以被不使用JRE设置的默认路由规划者使用的代理主机。这个参数期望得到一个HttpHost类型的值。如果这个参数没有被设置，那么就会尝试直接连接到目标。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.route.local-address'：定义一个本地地址由所有默认路由规划者来使用。有多个网络接口的机器中，这个参数可以被用于从连接源中选择网络接口。这个参数期望得到一个java.net.InetAddress类型的值。如果这个参数没有被设置，将会自动使用本地地址。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.route.forced-route'：定义一个由所有默认路由规划者使用的强制路由。代替了计算路由，给定的强制路由将会被返回，尽管它指向一个完全不同的目标主机。这个参数期望得到一个HttpRoute类型的值。如果这个参数没有被设置，那么就使用默认的规则建立连接到目标服务器。 </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.5 套接字工厂</h3>
<p style="font-family: inherit">LayeredSocketFactory是SocketFactory接口的扩展。分层的套接字工厂可HTTP连接内部使用java.net.Socket对象来处理数据在线路上的传输。它们依赖SocketFactory接口来创建，初始化和连接套接字。这会使得HttpClient的用户可以提供在运行时指定套接字初始化代码的应用程序。PlainSocketFactory是创建和初始化普通的（不加密的）套接字的默认工厂。</p>
<p style="font-family: inherit">创建套接字的过程和连接到主机的过程是不成对的，所以套接字在连接操作封锁时可以被关闭。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">PlainSocketFactory sf = PlainSocketFactory.getSocketFactory();</div>
<div style="font-family: inherit">Socket socket = sf.createSocket();</div>
<div style="font-family: inherit">HttpParams params = new BasicHttpParams();</div>
<div style="font-family: inherit">params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);</div>
<div style="font-family: inherit">sf.connectSocket(socket, "locahost", 8080, null, -1, params);</div></blockquote>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.5.1 安全套接字分层</h4>
<p style="font-family: inherit">LayeredSocketFactory是SocketFactory接口的扩展。分层的套接字工厂可以创建在已经存在的普通套接字之上的分层套接字。套接字分层主要通过代理来创建安全的套接字。HttpClient附带实现了SSL/TLS分层的SSLSocketFactory。请注意HttpClient不使用任何自定义加密功能。它完全依赖于标准的Java密码学（JCE）和安全套接字（JSEE）扩展。</p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.5.2 SSL/TLS的定制</h4>
<p style="font-family: inherit">HttpClient使用SSLSocketFactory来创建SSL连接。SSLSocketFactory允许高度定制。它可以使用javax.net.ssl.SSLContext的实例作为参数，并使用它来创建定制SSL连接。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">TrustManager easyTrustManager = new X509TrustManager() {</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public void checkClientTrusted(X509Certificate[] chain,</div>
<div style="font-family: inherit">String authType) throws CertificateException {</div>
<div style="font-family: inherit">// 哦，这很简单！</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public void checkServerTrusted(X509Certificate[] chain,</div>
<div style="font-family: inherit">String authType) throws CertificateException {</div>
<div style="font-family: inherit">//哦，这很简单！</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public X509Certificate[] getAcceptedIssuers() {</div>
<div style="font-family: inherit">return null;</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">};</div>
<div style="font-family: inherit">SSLContext sslcontext = SSLContext.getInstance("TLS");</div>
<div style="font-family: inherit">sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);</div>
<div style="font-family: inherit">SSLSocketFactory sf = new SSLSocketFactory(sslcontext);</div>
<div style="font-family: inherit">SSLSocket socket = (SSLSocket) sf.createSocket();</div>
<div style="font-family: inherit">socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });</div>
<div style="font-family: inherit">HttpParams params = new BasicHttpParams();</div>
<div style="font-family: inherit">params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);</div>
<div style="font-family: inherit">sf.connectSocket(socket, "locahost", 443, null, -1, params);</div></blockquote>
<div style="font-family: inherit">SSLSocketFactory的定制暗示出一定程度SSL/TLS协议概念的熟悉，这个详细的解释超出了本文档的范围。请参考Java的安全套接字扩展[http://java.sun.com/j2se/1.5.0/docs/guide/</div>
<div style="font-family: inherit">security/jsse/JSSERefGuide.html]，这是javax.net.ssl.SSLContext和相关工具的详细描述。</div>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.5.3 主机名验证</h4>
<div style="font-family: inherit">除了信任验证和客户端认证在SSL/TLS协议级上进行，一旦连接建立之后，HttpClient能可选地验证目标主机名匹配存储在服务器的X.509认证中的名字。这个认证可以提供额外的服务器信任材料的真实保证。X509主机名验证接口代表了主机名验证的策略。HttpClient附带了3个X509主机名验证器。很重要的一点是：主机名验证不应该混淆SSL信任验证。</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">StrictHostnameVerifier：严格的主机名验证在Sun Java 1.4，Sun Java 5和Sun Java 6中是相同的。而且也非常接近IE6。这个实现似乎是兼容RFC 2818处理通配符的。主机名必须匹配第一个CN或任意的subject-alt。在CN和其它任意的subject-alt中可能会出现通配符。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">BrowserCompatHostnameVerifier：主机名验证器和Curl和Firefox的工作方式是相同的。主机名必须匹配第一个CN或任意的subject-alt。在CN和其它任意的subject-alt中可能会出现通配符。BrowserCompatHostnameVerifier和StrictHostnameVerifier的唯一不同是使用BrowserCompatHostnameVerifier匹配所有子域的通配符（比如&#8221;*.foo.com&#8221;），包括&#8221;a.b.foo.com&#8221;。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">AllowAllHostnameVerifier：这个主机名验证器基本上是关闭主机名验证的。这个实现是一个空操作，而且不会抛出javax.net.ssl.SSLException异常。 </li></ul>
<p style="font-family: inherit">每一个默认的HttpClient使用BrowserCompatHostnameVerifier的实现。如果需要的话，它可以指定不同的主机名验证器实现。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));</div>
<div style="font-family: inherit">sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.6 协议模式</h3>
<p style="font-family: inherit">Scheme类代表了一个协议模式，比如&#8220;http&#8221;或&#8220;https&#8221;同时包含一些协议属性，比如默认端口，用来为给定协议创建java.net.Socket实例的套接字工厂。SchemeRegistry类用来维持一组Scheme，当去通过请求URI建立连接时，HttpClient可以从中选择：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);</div>
<div style="font-family: inherit">SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));</div>
<div style="font-family: inherit">sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);</div>
<div style="font-family: inherit">Scheme https = new Scheme("https", sf, 443);</div>
<div style="font-family: inherit">SchemeRegistry sr = new SchemeRegistry();</div>
<div style="font-family: inherit">sr.register(http);</div>
<div style="font-family: inherit">sr.register(https);</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.7 HttpClient代理配置</h3>
<p style="font-family: inherit">尽管HttpClient了解复杂的路由模式和代理链，它仅支持简单直接的或开箱的跳式代理连接。</p>
<p style="font-family: inherit">告诉HttpClient通过代理去连接到目标主机的最简单方式是通过设置默认的代理参数：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">HttpHost proxy = new HttpHost("someproxy", 8080);</div>
<div style="font-family: inherit">httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);</div></blockquote>
<p style="font-family: inherit">也可以构建HttpClient使用标准的JRE代理选择器来获得代理信息：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(</div>
<div style="font-family: inherit">httpclient.getConnectionManager().getSchemeRegistry(),</div>
<div style="font-family: inherit">ProxySelector.getDefault());</div>
<div style="font-family: inherit">httpclient.setRoutePlanner(routePlanner);</div></blockquote>
<p style="font-family: inherit">另外一种选择，可以提供一个定制的RoutePlanner实现来获得HTTP路由计算处理上的复杂的控制：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">httpclient.setRoutePlanner(new HttpRoutePlanner() {</div>
<div style="font-family: inherit">public HttpRoute determineRoute(HttpHost target,</div>
<div style="font-family: inherit">HttpRequest request,</div>
<div style="font-family: inherit">HttpContext context) throws HttpException {</div>
<div style="font-family: inherit">return new HttpRoute(target, null, new HttpHost("someproxy", 8080),</div>
<div style="font-family: inherit">"https".equalsIgnoreCase(target.getSchemeName()));</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">});</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.8 HTTP连接管理器</h3>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.8.1 连接操作器</h4>
<p style="font-family: inherit">连接操作是客户端的低层套接字或可以通过外部实体，通常称为连接操作的被操作的状态的连接。OperatedClientConnection接口扩展了HttpClientConnection接口而且定义了额外的控制连接套接字的方法。ClientConnectionOperator接口代表了创建实例和更新那些对象低层套接字的策略。实现类最有可能利用SocketFactory来创建java.net.Socket实例。ClientConnectionOperator接口可以让HttpClient的用户提供一个连接操作的定制策略和提供可选实现OperatedClientConnection接口的能力。</p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.8.2 管理连接和连接管理器</h4>
<p style="font-family: inherit">HTTP连接是复杂的，有状态的，线程不安全的对象需要正确的管理以便正确地执行功能。HTTP连接在同一时间仅仅只能由一个执行线程来使用。HttpClient采用一个特殊实体来管理访问HTTP连接，这被称为HTTP连接管理器，代表了ClientConnectionManager接口。一个HTTP连接管理器的目的是作为工厂服务于新的HTTP连接，管理持久连接和同步访问持久连接来确保同一时间仅有一个线程可以访问一个连接。</p>
<p style="font-family: inherit">内部的HTTP连接管理器和OperatedClientConnection实例一起工作，但是它们为服务消耗器ManagedClientConnection提供实例。ManagedClientConnection扮演连接之上管理状态控制所有I/O操作的OperatedClientConnection实例的包装器。它也抽象套接字操作，提供打开和更新去创建路由套接字便利的方法。ManagedClientConnection实例了解产生它们到连接管理器的链接，而且基于这个事实，当不再被使用时，它们必须返回到管理器。ManagedClientConnection类也实现了ConnectionReleaseTrigger接口，可以被用来触发释放连接返回给管理器。一旦释放连接操作被触发了，被包装的连接从ManagedClientConnection包装器中脱离，OperatedClientConnection实例被返回给管理器。尽管服务消耗器仍然持有ManagedClientConnection实例的引用，它也不再去执行任何I/O操作或有意无意地改变的OperatedClientConnection状态。</p>
<p style="font-family: inherit">这里有一个从连接管理器中获取连接的示例：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">HttpParams params = new BasicHttpParams();</div>
<div style="font-family: inherit">Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);</div>
<div style="font-family: inherit">SchemeRegistry sr = new SchemeRegistry();</div>
<div style="font-family: inherit">sr.register(http);</div>
<div style="font-family: inherit">ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);</div>
<div style="font-family: inherit">// 请求新连接。这可能是一个很长的过程。</div>
<div style="font-family: inherit">ClientConnectionRequest connRequest = connMrg.requestConnection(</div>
<div style="font-family: inherit">new HttpRoute(new HttpHost("localhost", 80)), null);</div>
<div style="font-family: inherit">// 等待连接10秒</div>
<div style="font-family: inherit">ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);</div>
<div style="font-family: inherit">try {</div>
<div style="font-family: inherit">// 用连接在做有用的事情。当完成时释放连接。</div>
<div style="font-family: inherit">conn.releaseConnection();</div>
<div style="font-family: inherit">} catch (IOException ex) {</div>
<div style="font-family: inherit">// 在I/O error之上终止连接。</div>
<div style="font-family: inherit">conn.abortConnection();</div>
<div style="font-family: inherit">throw ex;</div>
<div style="font-family: inherit">}</div></blockquote>
<p style="font-family: inherit">如果需要，连接请求可以通过调用来ClientConnectionRequest#abortRequest()方法过早地中断。这会解锁在ClientConnectionRequest#getConnection()方法中被阻止的线程。</p>
<p style="font-family: inherit">一旦响应内容被完全消耗后，BasicManagedEntity包装器类可以用来保证自动释放低层的连接。HttpClient内部使用这个机制来实现透明地对所有从HttpClient#execute()方法中获得响应释放连接：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">ClientConnectionRequest connRequest = connMrg.requestConnection(</div>
<div style="font-family: inherit">new HttpRoute(new HttpHost("localhost", 80)), null);</div>
<div style="font-family: inherit">ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);</div>
<div style="font-family: inherit">try {</div>
<div style="font-family: inherit">BasicHttpRequest request = new BasicHttpRequest("GET", "/");</div>
<div style="font-family: inherit">conn.sendRequestHeader(request);</div>
<div style="font-family: inherit">HttpResponse response = conn.receiveResponseHeader();</div>
<div style="font-family: inherit">conn.receiveResponseEntity(response);</div>
<div style="font-family: inherit">HttpEntity entity = response.getEntity();</div>
<div style="font-family: inherit">if (entity != null) {</div>
<div style="font-family: inherit">BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);</div>
<div style="font-family: inherit">// 替换实体</div>
<div style="font-family: inherit">response.setEntity(managedEntity);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">// 使用响应对象做有用的事情。当响应内容被消耗后这个连接将会自动释放。</div>
<div style="font-family: inherit">} catch (IOException ex) {</div>
<div style="font-family: inherit">//在I/O error之上终止连接。</div>
<div style="font-family: inherit">conn.abortConnection();</div>
<div style="font-family: inherit">throw ex;</div>
<div style="font-family: inherit">}</div></blockquote>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.8.3 简单连接管理器</h4>
<p style="font-family: inherit">SingleClientConnManager是一个简单的连接管理器，在同一时间它仅仅维护一个连接。尽管这个类是线程安全的，但它应该被用于一个执行线程。SingleClientConnManager对于同一路由的后续请求会尽量重用连接。而如果持久连接的路由不匹配连接请求的话，它也会关闭存在的连接之后对给定路由再打开一个新的。如果连接已经被分配，将会抛出java.lang.IllegalStateException异常。</p>
<p style="font-family: inherit">对于每个默认连接，HttpClient使用SingleClientConnManager。</p>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.8.4 连接池管理器</h4>
<p style="font-family: inherit">ThreadSafeClientConnManager是一个复杂的实现来管理客户端连接池，它也可以从多个执行线程中服务连接请求。对每个基本的路由，连接都是池管理的。对于路由的请求，管理器在池中有可用的持久性连接，将被从池中租赁连接服务，而不是创建一个新的连接。</p>
<p style="font-family: inherit">ThreadSafeClientConnManager维护每个基本路由的最大连接限制。每个默认的实现对每个给定路由将会创建不超过两个的并发连接，而总共也不会超过20个连接。对于很多真实的应用程序，这个限制也证明很大的制约，特别是他们在服务中使用HTTP作为传输协议。连接限制，也可以使用HTTP参数来进行调整。</p>
<p style="font-family: inherit">这个示例展示了连接池参数是如何来调整的：</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">HttpParams params = new BasicHttpParams();</div>
<div style="font-family: inherit">// 增加最大连接到200</div>
<div style="font-family: inherit">ConnManagerParams.setMaxTotalConnections(params, 200);</div>
<div style="font-family: inherit">// 增加每个路由的默认最大连接到20</div>
<div style="font-family: inherit">ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);</div>
<div style="font-family: inherit">// 对localhost:80增加最大连接到50</div>
<div style="font-family: inherit">HttpHost localhost = new HttpHost("locahost", 80);</div>
<div style="font-family: inherit">connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50);</div>
<div style="font-family: inherit">ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);</div>
<div style="font-family: inherit">SchemeRegistry schemeRegistry = new SchemeRegistry();</div>
<div style="font-family: inherit">schemeRegistry.register(</div>
<div style="font-family: inherit">new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));</div>
<div style="font-family: inherit">schemeRegistry.register(</div>
<div style="font-family: inherit">new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));</div>
<div style="font-family: inherit">ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);</div>
<div style="font-family: inherit">HttpClient httpClient = new DefaultHttpClient(cm, params);</div></blockquote>
<h4 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.8.5 连接管理器关闭</h4>
<p style="font-family: inherit">当一个HttpClient实例不再需要时，而且即将走出使用范围，那么关闭连接管理器来保证由管理器保持活动的所有连接被关闭，由连接分配的系统资源被释放是很重要的。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">HttpGet httpget = new HttpGet("http://www.google.com/");</div>
<div style="font-family: inherit">HttpResponse response = httpclient.execute(httpget);</div>
<div style="font-family: inherit">HttpEntity entity = response.getEntity();</div>
<div style="font-family: inherit">System.out.println(response.getStatusLine());</div>
<div style="font-family: inherit">if (entity != null) {</div>
<div style="font-family: inherit">entity.consumeContent();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">httpclient.getConnectionManager().shutdown();</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.9 连接管理参数</h3>
<div style="font-family: inherit">这些是可以用于定制标准HTTP连接管理器实现的参数：</div>
<ul style="font-family: Verdana, Arial, Tahoma, sans-serif"><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.conn-manager.timeout'：定义了当从ClientConnectionManager中检索ManagedClientConnection实例时使用的毫秒级的超时时间。这个参数期望得到一个java.lang.Long类型的值。如果这个参数没有被设置，连接请求就不会超时（无限大的超时时间）。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.conn-manager.max-per-route'：定义了每个路由连接的最大数量。这个限制由客户端连接管理器来解释，而且应用于独立的管理器实例。这个参数期望得到一个ConnPerRoute类型的值。</li><li style="font-family: Verdana, Arial, Tahoma, sans-serif">'http.conn-manager.max-total'：定义了总共连接的最大数目。这个限制由客户端连接管理器来解释，而且应用于独立的管理器实例。这个参数期望得到一个java.lang.Integer类型的值。 </li></ul>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.10 多线程执行请求</h3>
<p style="font-family: inherit">当配备连接池管理器时，比如ThreadSafeClientConnManager，HttpClient可以同时被用来执行多个请求，使用多线程执行。</p>
<p style="font-family: inherit">ThreadSafeClientConnManager将会分配基于它的配置的连接。如果对于给定路由的所有连接都被租出了，那么连接的请求将会阻塞，直到一个连接被释放回连接池。它可以通过设置'http.conn-manager.timeout'为一个正数来保证连接管理器不会在连接请求执行时无限期的被阻塞。如果连接请求不能在给定的时间周期内被响应，将会抛出ConnectionPoolTimeoutException异常。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">HttpParams params = new BasicHttpParams();</div>
<div style="font-family: inherit">SchemeRegistry schemeRegistry = new SchemeRegistry();</div>
<div style="font-family: inherit">schemeRegistry.register(</div>
<div style="font-family: inherit">new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));</div>
<div style="font-family: inherit">ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);</div>
<div style="font-family: inherit">HttpClient httpClient = new DefaultHttpClient(cm, params);</div>
<div style="font-family: inherit">// 执行GET方法的URI</div>
<div style="font-family: inherit">String[] urisToGet = {</div>
<div style="font-family: inherit">"http://www.domain1.com/",</div>
<div style="font-family: inherit">"http://www.domain2.com/",</div>
<div style="font-family: inherit">"http://www.domain3.com/",</div>
<div style="font-family: inherit">"http://www.domain4.com/"</div>
<div style="font-family: inherit">};</div>
<div style="font-family: inherit">// 为每个URI创建一个线程</div>
<div style="font-family: inherit">GetThread[] threads = new GetThread[urisToGet.length];</div>
<div style="font-family: inherit">for (int i = 0; i &lt; threads.length; i++) {</div>
<div style="font-family: inherit">HttpGet httpget = new HttpGet(urisToGet[i]);</div>
<div style="font-family: inherit">threads[i] = new GetThread(httpClient, httpget);</div>
<div style="font-family: inherit">}</div></blockquote>
<div style="font-family: inherit">
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">// 开始执行线程</div>
<div style="font-family: inherit">for (int j = 0; j &lt; threads.length; j++) {</div>
<div style="font-family: inherit">threads[j].start();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">// 合并线程</div>
<div style="font-family: inherit">for (int j = 0; j &lt; threads.length; j++) {</div>
<div style="font-family: inherit">threads[j].join();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">&nbsp;</div>
<div style="font-family: inherit">
<div style="font-family: inherit">static class GetThread extends Thread {</div>
<div style="font-family: inherit">private final HttpClient httpClient;</div>
<div style="font-family: inherit">private final HttpContext context;</div>
<div style="font-family: inherit">private final HttpGet httpget;</div>
<div style="font-family: inherit">public GetThread(HttpClient httpClient, HttpGet httpget) {</div>
<div style="font-family: inherit">this.httpClient = httpClient;</div>
<div style="font-family: inherit">this.context = new BasicHttpContext();</div>
<div style="font-family: inherit">this.httpget = httpget;</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public void run() {</div>
<div style="font-family: inherit">try {</div>
<div style="font-family: inherit">HttpResponse response = this.httpClient.execute(this.httpget, this.context);</div>
<div style="font-family: inherit">HttpEntity entity = response.getEntity();</div>
<div style="font-family: inherit">if (entity != null) {</div>
<div style="font-family: inherit">// 对实体做些有用的事情...</div>
<div style="font-family: inherit">// 保证连接能释放回管理器</div>
<div style="font-family: inherit">entity.consumeContent();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">} catch (Exception ex) {</div>
<div style="font-family: inherit">this.httpget.abort();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div></div></blockquote></div>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.11 连接收回策略</h3>
<p style="font-family: inherit">一个经典的阻塞I/O模型的主要缺点是网络套接字仅当I/O操作阻塞时才可以响应I/O事件。当一个连接被释放返回管理器时，它可以被保持活动状态而却不能监控套接字的状态和响应任何I/O事件。如果连接在服务器端关闭，那么客户端连接也不能去侦测连接状态中的变化和关闭本端的套接字去作出适当响应。</p>
<p style="font-family: inherit">HttpClient通过测试连接是否是过时的来尝试去减轻这个问题，这已经不再有效了，因为它已经在服务器端关闭了，之前使用执行HTTP请求的连接。过时的连接检查也并不是100%的稳定，反而对每次请求执行还要增加10到30毫秒的开销。唯一可行的而不涉及到每个对空闲连接的套接字模型线程解决方案，是使用专用的监控线程来收回因为长时间不活动而被认为是过期的连接。监控线程可以周期地调用ClientConnectionManager#closeExpiredConnections()方法来关闭所有过期的连接，从连接池中收回关闭的连接。它也可以选择性调用ClientConnectionManager#closeIdleConnections()方法来关闭所有已经空闲超过给定时间周期的连接。</p>
<blockquote style="background-image: url(http://simpleframework.net/$resource/default/css/blue/images/quote.png); border-bottom: #dddddd 2px dashed; border-left: #dddddd 2px dashed; padding-bottom: 8px !important; background-color: #f9f9ff; margin: 4px 2px; padding-left: 40px !important; padding-right: 6px !important; font-family: Verdana, Arial, Tahoma, sans-serif; background-position: 4px 0px; border-top: #dddddd 2px dashed; border-right: #dddddd 2px dashed; padding-top: 8px !important; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px; background-origin: initial; background-clip: initial">
<div style="font-family: inherit">public static class IdleConnectionMonitorThread extends Thread {</div>
<div style="font-family: inherit">private final ClientConnectionManager connMgr;</div>
<div style="font-family: inherit">private volatile boolean shutdown;</div>
<div style="font-family: inherit">public IdleConnectionMonitorThread(ClientConnectionManager connMgr) {</div>
<div style="font-family: inherit">super();</div>
<div style="font-family: inherit">this.connMgr = connMgr;</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">@Override</div>
<div style="font-family: inherit">public void run() {</div>
<div style="font-family: inherit">try {</div>
<div style="font-family: inherit">while (!shutdown) {</div>
<div style="font-family: inherit">synchronized (this) {</div>
<div style="font-family: inherit">wait(5000);</div>
<div style="font-family: inherit">// 关闭过期连接</div>
<div style="font-family: inherit">connMgr.closeExpiredConnections();</div>
<div style="font-family: inherit">// 可选地，关闭空闲超过30秒的连接</div>
<div style="font-family: inherit">connMgr.closeIdleConnections(30, TimeUnit.SECONDS);</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">} catch (InterruptedException ex) {</div>
<div style="font-family: inherit">// 终止</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">public void shutdown() {</div>
<div style="font-family: inherit">shutdown = true;</div>
<div style="font-family: inherit">synchronized (this) {</div>
<div style="font-family: inherit">notifyAll();</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div></blockquote>
<h3 style="font-family: Verdana, Arial, Tahoma, sans-serif">2.12 连接保持活动的策略</h3>
<p style="font-family: inherit">HTTP规范没有确定一个持久连接可能或应该保持活动多长时间。一些HTTP服务器使用非标准的头部信息Keep-Alive来告诉客户端它们想在服务器端保持连接活动的周期秒数。如果这个信息可用，HttClient就会利用这个它。如果头部信息Keep-Alive在响应中不存在，HttpClient假设连接无限期的保持活动。然而许多现实中的HTTP服务器配置了在特定不活动周期之后丢掉持久连接来保存系统资源，往往这是不通知客户端的。如果默认的策略证明是过于乐观的，那么就会有人想提供一个定制的保持活动策略。</p>
<p style="font-family: inherit"></p>
<div style="font-family: inherit">DefaultHttpClient httpclient = new DefaultHttpClient();</div>
<div style="font-family: inherit">httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {</div>
<div style="font-family: inherit">public long getKeepAliveDuration(HttpResponse response, HttpContext context) {</div>
<div style="font-family: inherit">// 兑现'keep-alive'头部信息</div>
<div style="font-family: inherit">HeaderElementIterator it = new BasicHeaderElementIterator(</div>
<div style="font-family: inherit">response.headerIterator(HTTP.CONN_KEEP_ALIVE));</div>
<div style="font-family: inherit">while (it.hasNext()) {</div>
<div style="font-family: inherit">HeaderElement he = it.nextElement();</div>
<div style="font-family: inherit">String param = he.getName();</div>
<div style="font-family: inherit">String value = he.getValue();</div>
<div style="font-family: inherit">if (value != null &amp;&amp; param.equalsIgnoreCase("timeout")) {</div>
<div style="font-family: inherit">try {</div>
<div style="font-family: inherit">return Long.parseLong(value) * 1000;</div>
<div style="font-family: inherit">} catch(NumberFormatException ignore) {</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">HttpHost target = (HttpHost) context.getAttribute(</div>
<div style="font-family: inherit">ExecutionContext.HTTP_TARGET_HOST);</div>
<div style="font-family: inherit">if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {</div>
<div style="font-family: inherit">// 只保持活动5秒</div>
<div style="font-family: inherit">return 5 * 1000;</div>
<div style="font-family: inherit">} else {</div>
<div style="font-family: inherit">// 否则保持活动30秒</div>
<div style="font-family: inherit">return 30 * 1000;</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">}</div>
<div style="font-family: inherit">});　</div>
<p>&nbsp;</p></div><br /><br />转载自：<a href="http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112832.html">http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112832.html</a></div><img src ="http://www.blogjava.net/stevenjohn/aggbug/388604.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:42 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388604.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient 教程 (一) </title><link>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388603.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 26 Sep 2012 08:41:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388603.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/388603.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/09/26/388603.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/388603.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/388603.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: 前言超文本传输协议（HTTP）也许是当今互联网上使用的最重要的协议了。Web服务，有网络功能的设备和网络计算的发展，都持续扩展了HTTP协议的角色，超越了用户使用的Web浏览器范畴，同时，也增加了需要HTTP协议支持的应用程序的数量。尽管java.net包提供了基本通过HTTP访问资源的功能，但它没有提供全面的灵活性和其它很多应用程序需要的功能。HttpClient就是寻求弥补这项空白...&nbsp;&nbsp;<a href='http://www.blogjava.net/stevenjohn/archive/2012/09/26/388603.html'>阅读全文</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/388603.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-09-26 16:41 <a href="http://www.blogjava.net/stevenjohn/archive/2012/09/26/388603.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpsURLConnection 安全传输（HTTPS--Secure Hypertext Transfer Protocol-安全超文本传输协议） </title><link>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385569.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Thu, 16 Aug 2012 01:48:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385569.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/385569.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385569.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/385569.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/385569.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: HttpsURLConnection 扩展 HttpURLConnection，支持各种特定于 https 功能。此类使用 HostnameVerifier 和 SSLSocketFactory。为这两个类都定义了默认实现。但是，可以根据每个类（静态的）或每个实例来替换该实现。所有新 HttpsURLConnection 实例在创建时将被分配&#8220;默认的&#8221;静态值，通过在连接前调...&nbsp;&nbsp;<a href='http://www.blogjava.net/stevenjohn/archive/2012/08/16/385569.html'>阅读全文</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/385569.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-08-16 09:48 <a href="http://www.blogjava.net/stevenjohn/archive/2012/08/16/385569.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>A Java HTTPS client example</title><link>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385561.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 15 Aug 2012 16:41:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385561.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/385561.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385561.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/385561.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/385561.html</trackback:ping><description><![CDATA[<p>Java HTTPS Client FAQ: Can you share some source code for a Java HTTPS client application?</p>
<p>Sure, here's the source code for an example <em>Java HTTPS</em> client program I&nbsp;just used to download the contents of an HTTPS (SSL) URL. I actually found some of this in a newsgroup a while ago, but I&nbsp;can't find the source today to give them credit, so my apologies for that.</p>
<p>I just used this program to troubleshoot a problem with Java and HTTPS URLs, including all that nice Java SSL <em>keystore</em> and <em>cacerts</em> stuff you may run into when working with Java, HTTPS/SSL, and hitting a URL.</p>
<p>This Java program should work if you are hitting an HTTPS URL that has a valid SSL certificate from someone like Verisign or Thawte, but will not work with other SSL certificates unless you go down the Java keystore road.</p>
<h2>Example Java HTTPS client program</h2>
<p>Here's the source code for my simple Java HTTPS client program:</p><br /><br /><br />package foo;<br /><br />import java.net.URL;<br />import java.io.*;<br />import javax.net.ssl.HttpsURLConnection;<br /><br />public class JavaHttpsExample<br />{<br />&nbsp; public static void main(String[] args)<br />&nbsp; throws Exception<br />&nbsp; {<br />&nbsp;&nbsp;&nbsp; String httpsURL = "https://your.https.url.here/";<br />&nbsp;&nbsp;&nbsp; URL myurl = new URL(httpsURL);<br />&nbsp;&nbsp;&nbsp; HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();<br />&nbsp;&nbsp;&nbsp; InputStream ins = con.getInputStream();<br />&nbsp;&nbsp;&nbsp; InputStreamReader isr = new InputStreamReader(ins);<br />&nbsp;&nbsp;&nbsp; BufferedReader in = new BufferedReader(isr);<br /><br />&nbsp;&nbsp;&nbsp; String inputLine;<br /><br />&nbsp;&nbsp;&nbsp; while ((inputLine = in.readLine()) != null)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(inputLine);<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; in.close();<br />&nbsp; }<br />}<br /><br /><br /><br /><br /><br /><br />
<p>Just change the URL shown there to the HTTPS URL you want to access, and hopefully everything will work well for you. (If not, there's always that Comment section down below, lol.)</p><br /><br /><br /><a href="http://www.devdaily.com/blog/post/java/simple-https-example">http://www.devdaily.com/blog/post/java/simple-https-example</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/385561.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-08-16 00:41 <a href="http://www.blogjava.net/stevenjohn/archive/2012/08/16/385561.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>java SSL https </title><link>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385560.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 15 Aug 2012 16:35:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385560.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/385560.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385560.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/385560.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/385560.html</trackback:ping><description><![CDATA[<p>package org.abin.lee;</p>
<p>import java.security.cert.CertificateException;<br />import java.security.cert.X509Certificate;</p>
<p>import javax.net.ssl.X509TrustManager;<br />&nbsp;&nbsp; </p>
<p>/**&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;* 自定义的认证管理类。&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;* @author JAVA世纪网(java2000.net)&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;*/&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />class Java2000TrustManager implements X509TrustManager {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; Java2000TrustManager() {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; // 这里可以进行证书的初始化操作&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; // 检查客户端的可信任状态&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; public void checkClientTrusted(X509Certificate chain[], String authType) throws CertificateException {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; System.out.println("检查客户端的可信任状态...");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; // 检查服务器的可信任状态&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; public void checkServerTrusted(X509Certificate chain[], String authType) throws CertificateException {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; System.out.println("检查服务器的可信任状态");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; // 返回接受的发行商数组&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; public X509Certificate[] getAcceptedIssuers() {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; System.out.println("获取接受的发行商数组...");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; return null;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />}&nbsp;&nbsp;&nbsp;&nbsp; </p><br /><br /><br /><br /><br /><br /><br />
<p>package org.abin.lee;</p>
<p>import java.io.BufferedReader;<br />import java.io.BufferedWriter;<br />import java.io.InputStreamReader;<br />import java.io.OutputStreamWriter;<br />import java.net.Socket;</p>
<p>import javax.net.ssl.SSLContext;<br />import javax.net.ssl.SSLSocketFactory;<br />import javax.net.ssl.TrustManager;<br />import javax.net.ssl.X509TrustManager;</p>
<p>/**<br />&nbsp;* JAVA操作SSL协议，通过Socket访问Https的程序代码例子。<br />&nbsp;* <br />&nbsp;* @author JAVA世纪网(java2000.net)<br />&nbsp;* <br />&nbsp;*/<br />public class ReadHttpsURL {<br />&nbsp;// 默认的HTTPS 端口<br />&nbsp;static final int HTTPS_PORT = 443;</p>
<p>&nbsp;public static void main(String argv[]) throws Exception {<br />&nbsp;&nbsp;// 受访主机<br />&nbsp;&nbsp;String host = "<a href="http://www.google.com">www.google.com</a>";<br />&nbsp;&nbsp;// 受访的页面<br />&nbsp;&nbsp;String url = "/adsense/?sourceid=aso&amp;subid=ZH_CN-ET-AS-ADSBY6&amp;medium=link&amp;hl=zh_CN";<br />&nbsp;&nbsp;// 自定义的管理器<br />&nbsp;&nbsp;X509TrustManager xtm = new Java2000TrustManager();<br />&nbsp;&nbsp;TrustManager mytm[] = { xtm };<br />&nbsp;&nbsp;// 得到上下文<br />&nbsp;&nbsp;SSLContext ctx = SSLContext.getInstance("SSL");<br />&nbsp;&nbsp;// 初始化<br />&nbsp;&nbsp;ctx.init(null, mytm, null);<br />&nbsp;&nbsp;// 获得工厂<br />&nbsp;&nbsp;SSLSocketFactory factory = ctx.getSocketFactory();<br />&nbsp;&nbsp;// 从工厂获得Socket连接<br />&nbsp;&nbsp;Socket socket = factory.createSocket(host, HTTPS_PORT);<br />&nbsp;&nbsp;// 剩下的就和普通的Socket操作一样了<br />&nbsp;&nbsp;BufferedWriter out = new BufferedWriter(new OutputStreamWriter(<br />&nbsp;&nbsp;&nbsp;&nbsp;socket.getOutputStream()));<br />&nbsp;&nbsp;BufferedReader in = new BufferedReader(new InputStreamReader(<br />&nbsp;&nbsp;&nbsp;&nbsp;socket.getInputStream()));<br />&nbsp;&nbsp;out.write("GET " + url + " HTTP/1.0\n\n");<br />&nbsp;&nbsp;out.flush();<br />&nbsp;&nbsp;System.out.println("start&nbsp;&nbsp; work!");<br />&nbsp;&nbsp;String line;<br />&nbsp;&nbsp;StringBuffer sb = new StringBuffer();<br />&nbsp;&nbsp;while ((line = in.readLine()) != null) {<br />&nbsp;&nbsp;&nbsp;sb.append(line + "\n");<br />&nbsp;&nbsp;}<br />&nbsp;&nbsp;out.close();<br />&nbsp;&nbsp;in.close();<br />&nbsp;&nbsp;System.out.println(sb.toString());<br />&nbsp;}<br />}<br /><br /><br /><br /><br /><br /><a href="http://ming-fanglin.iteye.com/blog/574596">http://ming-fanglin.iteye.com/blog/574596</a></p><img src ="http://www.blogjava.net/stevenjohn/aggbug/385560.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-08-16 00:35 <a href="http://www.blogjava.net/stevenjohn/archive/2012/08/16/385560.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java HTTPS Client – HttpsURLConnection Example</title><link>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385559.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 15 Aug 2012 16:17:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385559.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/385559.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/08/16/385559.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/385559.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/385559.html</trackback:ping><description><![CDATA[<span style="widows: 2; text-transform: none; background-color: rgb(255,255,255); text-indent: 0px; font: 14px/21px 'Droid Sans', Helvetica, Arial, sans-serif; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(60,60,60); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px" class="Apple-style-span"> 
<p style="margin: 0px 0px 20px">Here&#8217;s a simple Java HTTPS client to demonstrate the use of<span class="Apple-converted-space">&nbsp;</span><code style="border-bottom: rgb(225,225,232) 1px solid; border-left: rgb(225,225,232) 1px solid; padding-bottom: 2px; background-color: rgb(247,247,249); padding-left: 4px; padding-right: 4px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; color: rgb(15,59,104); font-size: 13px; border-top: rgb(225,225,232) 1px solid; border-right: rgb(225,225,232) 1px solid; padding-top: 2px; border-top-left-radius: 3px 3px; border-top-right-radius: 3px 3px; border-bottom-right-radius: 3px 3px; border-bottom-left-radius: 3px 3px">HttpsURLConnection</code><span class="Apple-converted-space">&nbsp;</span>class to print a https URL content and certificate detail.</p>
<p style="margin: 0px 0px 20px"><em style="font-style: italic">Access https URL : https://www.google.com/</em></p></span><br /><span style="widows: 2; text-transform: none; background-color: rgb(255,255,255); text-indent: 0px; font: 14px/21px 'Droid Sans', Helvetica, Arial, sans-serif; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(60,60,60); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px" class="Apple-style-span"> 
<div class="wp_syntax">
<div class="code"><pre style="border-bottom: 1px solid; border-left: 1px solid; padding-bottom: 10px !important; line-height: 1.5; background-color: rgb(245,245,245); padding-left: 10px !important; padding-right: 10px !important; display: block; font-family: monospace; word-wrap: break-word; white-space: pre-wrap; color: rgb(51,51,51); font-size: 12px; word-break: break-all; border-top: 1px solid; border-right: 1px solid; padding-top: 10px !important; border-top-left-radius: 4px 4px; border-top-right-radius: 4px 4px; border-bottom-right-radius: 4px 4px; border-bottom-left-radius: 4px 4px" class="java"><span style="color: rgb(0,0,0); font-weight: bold">package</span> <span style="color: rgb(0,102,153)">com.mkyong.client</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
<span style="color: rgb(0,0,0); font-weight: bold">import</span> <span style="color: rgb(0,102,153)">java.net.MalformedURLException</span><span style="color: rgb(51,153,51)">;</span>
<span style="color: rgb(0,0,0); font-weight: bold">import</span> <span style="color: rgb(0,102,153)">java.net.URL</span><span style="color: rgb(51,153,51)">;</span>
<span style="color: rgb(0,0,0); font-weight: bold">import</span> <span style="color: rgb(0,102,153)">java.security.cert.Certificate</span><span style="color: rgb(51,153,51)">;</span>
<span style="color: rgb(0,0,0); font-weight: bold">import</span> <span style="color: rgb(0,102,153)">java.io.*</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
<span style="color: rgb(0,0,0); font-weight: bold">import</span> <span style="color: rgb(0,102,153)">javax.net.ssl.HttpsURLConnection</span><span style="color: rgb(51,153,51)">;</span>
<span style="color: rgb(0,0,0); font-weight: bold">import</span> <span style="color: rgb(0,102,153)">javax.net.ssl.SSLPeerUnverifiedException</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
<span style="color: rgb(0,0,0); font-weight: bold">public</span> <span style="color: rgb(0,0,0); font-weight: bold">class</span> HttpsClient<span style="color: rgb(0,153,0)">{</span>
&nbsp;
   <span style="color: rgb(0,0,0); font-weight: bold">public</span> <span style="color: rgb(0,0,0); font-weight: bold">static</span> <span style="color: rgb(0,0,102); font-weight: bold">void</span> main<span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,51,153)">String</span><span style="color: rgb(0,153,0)">[</span><span style="color: rgb(0,153,0)">]</span> args<span style="color: rgb(0,153,0)">)</span>
   <span style="color: rgb(0,153,0)">{</span>
        <span style="color: rgb(0,0,0); font-weight: bold">new</span> HttpsClient<span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span>.<span style="color: rgb(0,102,51)">testIt</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
   <span style="color: rgb(0,153,0)">}</span>
&nbsp;
   <span style="color: rgb(0,0,0); font-weight: bold">private</span> <span style="color: rgb(0,0,102); font-weight: bold">void</span> testIt<span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
&nbsp;
      <span style="color: rgb(0,51,153)">String</span> https_url <span style="color: rgb(51,153,51)">=</span> <span style="color: rgb(0,0,255)">"https://www.google.com/"</span><span style="color: rgb(51,153,51)">;</span>
      <span style="color: rgb(0,51,153)">URL</span> url<span style="color: rgb(51,153,51)">;</span>
      <span style="color: rgb(0,0,0); font-weight: bold">try</span> <span style="color: rgb(0,153,0)">{</span>
&nbsp;
	     url <span style="color: rgb(51,153,51)">=</span> <span style="color: rgb(0,0,0); font-weight: bold">new</span> <span style="color: rgb(0,51,153)">URL</span><span style="color: rgb(0,153,0)">(</span>https_url<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	     HttpsURLConnection con <span style="color: rgb(51,153,51)">=</span> <span style="color: rgb(0,153,0)">(</span>HttpsURLConnection<span style="color: rgb(0,153,0)">)</span>url.<span style="color: rgb(0,102,51)">openConnection</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
	     <span style="font-style: italic; color: rgb(102,102,102)">//dumpl all cert info</span>
	     print_https_cert<span style="color: rgb(0,153,0)">(</span>con<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
	     <span style="font-style: italic; color: rgb(102,102,102)">//dump all the content</span>
	     print_content<span style="color: rgb(0,153,0)">(</span>con<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
      <span style="color: rgb(0,153,0)">}</span> <span style="color: rgb(0,0,0); font-weight: bold">catch</span> <span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,51,153)">MalformedURLException</span> e<span style="color: rgb(0,153,0)">)</span> <span style="color: rgb(0,153,0)">{</span>
	     e.<span style="color: rgb(0,102,51)">printStackTrace</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
      <span style="color: rgb(0,153,0)">}</span> <span style="color: rgb(0,0,0); font-weight: bold">catch</span> <span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,51,153)">IOException</span> e<span style="color: rgb(0,153,0)">)</span> <span style="color: rgb(0,153,0)">{</span>
	     e.<span style="color: rgb(0,102,51)">printStackTrace</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
      <span style="color: rgb(0,153,0)">}</span>
&nbsp;
   <span style="color: rgb(0,153,0)">}</span>
&nbsp;
   <span style="color: rgb(0,0,0); font-weight: bold">private</span> <span style="color: rgb(0,0,102); font-weight: bold">void</span> print_https_cert<span style="color: rgb(0,153,0)">(</span>HttpsURLConnection con<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
&nbsp;
    <span style="color: rgb(0,0,0); font-weight: bold">if</span><span style="color: rgb(0,153,0)">(</span>con<span style="color: rgb(51,153,51)">!=</span><span style="color: rgb(0,0,102); font-weight: bold">null</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
&nbsp;
      <span style="color: rgb(0,0,0); font-weight: bold">try</span> <span style="color: rgb(0,153,0)">{</span>
&nbsp;
	<span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"Response Code : "</span> <span style="color: rgb(51,153,51)">+</span> con.<span style="color: rgb(0,102,51)">getResponseCode</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"Cipher Suite : "</span> <span style="color: rgb(51,153,51)">+</span> con.<span style="color: rgb(0,102,51)">getCipherSuite</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"<span style="color: rgb(0,0,153); font-weight: bold">\n</span>"</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
	<span style="color: rgb(0,51,153)">Certificate</span><span style="color: rgb(0,153,0)">[</span><span style="color: rgb(0,153,0)">]</span> certs <span style="color: rgb(51,153,51)">=</span> con.<span style="color: rgb(0,102,51)">getServerCertificates</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,0,0); font-weight: bold">for</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,51,153)">Certificate</span> cert <span style="color: rgb(51,153,51)">:</span> certs<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
	   <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"Cert Type : "</span> <span style="color: rgb(51,153,51)">+</span> cert.<span style="color: rgb(0,102,51)">getType</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	   <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"Cert Hash Code : "</span> <span style="color: rgb(51,153,51)">+</span> cert.<span style="color: rgb(0,102,51)">hashCode</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	   <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"Cert Public Key Algorithm : "</span> <span style="color: rgb(51,153,51)">+</span> cert.<span style="color: rgb(0,102,51)">getPublicKey</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span>.<span style="color: rgb(0,102,51)">getAlgorithm</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	   <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"Cert Public Key Format : "</span> <span style="color: rgb(51,153,51)">+</span> cert.<span style="color: rgb(0,102,51)">getPublicKey</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span>.<span style="color: rgb(0,102,51)">getFormat</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	   <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"<span style="color: rgb(0,0,153); font-weight: bold">\n</span>"</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,153,0)">}</span>
&nbsp;
	<span style="color: rgb(0,153,0)">}</span> <span style="color: rgb(0,0,0); font-weight: bold">catch</span> <span style="color: rgb(0,153,0)">(</span>SSLPeerUnverifiedException e<span style="color: rgb(0,153,0)">)</span> <span style="color: rgb(0,153,0)">{</span>
		e.<span style="color: rgb(0,102,51)">printStackTrace</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,153,0)">}</span> <span style="color: rgb(0,0,0); font-weight: bold">catch</span> <span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,51,153)">IOException</span> e<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
		e.<span style="color: rgb(0,102,51)">printStackTrace</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,153,0)">}</span>
&nbsp;
     <span style="color: rgb(0,153,0)">}</span>
&nbsp;
   <span style="color: rgb(0,153,0)">}</span>
&nbsp;
   <span style="color: rgb(0,0,0); font-weight: bold">private</span> <span style="color: rgb(0,0,102); font-weight: bold">void</span> print_content<span style="color: rgb(0,153,0)">(</span>HttpsURLConnection con<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
	<span style="color: rgb(0,0,0); font-weight: bold">if</span><span style="color: rgb(0,153,0)">(</span>con<span style="color: rgb(51,153,51)">!=</span><span style="color: rgb(0,0,102); font-weight: bold">null</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
&nbsp;
	<span style="color: rgb(0,0,0); font-weight: bold">try</span> <span style="color: rgb(0,153,0)">{</span>
&nbsp;
	   <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,0,255)">"****** Content of the URL ********"</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>			
	   <span style="color: rgb(0,51,153)">BufferedReader</span> br <span style="color: rgb(51,153,51)">=</span> 
		<span style="color: rgb(0,0,0); font-weight: bold">new</span> <span style="color: rgb(0,51,153)">BufferedReader</span><span style="color: rgb(0,153,0)">(</span>
			<span style="color: rgb(0,0,0); font-weight: bold">new</span> <span style="color: rgb(0,51,153)">InputStreamReader</span><span style="color: rgb(0,153,0)">(</span>con.<span style="color: rgb(0,102,51)">getInputStream</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
	   <span style="color: rgb(0,51,153)">String</span> input<span style="color: rgb(51,153,51)">;</span>
&nbsp;
	   <span style="color: rgb(0,0,0); font-weight: bold">while</span> <span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">(</span>input <span style="color: rgb(51,153,51)">=</span> br.<span style="color: rgb(0,102,51)">readLine</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">)</span> <span style="color: rgb(51,153,51)">!=</span> <span style="color: rgb(0,0,102); font-weight: bold">null</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(0,153,0)">{</span>
	      <span style="color: rgb(0,51,153)">System</span>.<span style="color: rgb(0,102,51)">out</span>.<span style="color: rgb(0,102,51)">println</span><span style="color: rgb(0,153,0)">(</span>input<span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	   <span style="color: rgb(0,153,0)">}</span>
	   br.<span style="color: rgb(0,102,51)">close</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
&nbsp;
	<span style="color: rgb(0,153,0)">}</span> <span style="color: rgb(0,0,0); font-weight: bold">catch</span> <span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,51,153)">IOException</span> e<span style="color: rgb(0,153,0)">)</span> <span style="color: rgb(0,153,0)">{</span>
	   e.<span style="color: rgb(0,102,51)">printStackTrace</span><span style="color: rgb(0,153,0)">(</span><span style="color: rgb(0,153,0)">)</span><span style="color: rgb(51,153,51)">;</span>
	<span style="color: rgb(0,153,0)">}</span>
&nbsp;
       <span style="color: rgb(0,153,0)">}</span>
&nbsp;
   <span style="color: rgb(0,153,0)">}</span>
&nbsp;
<span style="color: rgb(0,153,0)">}</span></pre></div></div>
<p style="margin: 0px 0px 20px">Output&#8230;</p>
<div class="wp_syntax">
<div class="code"><pre style="border-bottom: 1px solid; border-left: 1px solid; padding-bottom: 10px !important; line-height: 1.5; background-color: rgb(245,245,245); padding-left: 10px !important; padding-right: 10px !important; display: block; font-family: monospace; word-wrap: break-word; white-space: pre-wrap; color: rgb(51,51,51); font-size: 12px; word-break: break-all; border-top: 1px solid; border-right: 1px solid; padding-top: 10px !important; border-top-left-radius: 4px 4px; border-top-right-radius: 4px 4px; border-bottom-right-radius: 4px 4px; border-bottom-left-radius: 4px 4px" class="bash">Response Code : <span style="color: rgb(0,0,0)">200</span>
Cipher Suite : SSL_RSA_WITH_RC4_128_SHA
&nbsp;
Cert Type : X.509
Cert Hash Code : <span style="color: rgb(0,0,0)">7810131</span>
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509
&nbsp;
Cert Type : X.509
Cert Hash Code : <span style="color: rgb(0,0,0)">6042770</span>
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509
&nbsp;
<span style="color: rgb(0,0,0); font-weight: bold">******</span> Content of the URL <span style="color: rgb(0,0,0); font-weight: bold">********</span>
<span style="color: rgb(0,0,0); font-weight: bold">&lt;!</span>doctype html<span style="color: rgb(0,0,0); font-weight: bold">&gt;&lt;</span>html<span style="color: rgb(0,0,0); font-weight: bold">&gt;&lt;</span><span style="color: rgb(194,12,185); font-weight: bold">head</span><span style="color: rgb(0,0,0); font-weight: bold">&gt;&lt;</span>meta http-equiv=<span style="color: rgb(255,0,0)">"content-type"</span> ......</pre></div></div></span><img src ="http://www.blogjava.net/stevenjohn/aggbug/385559.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-08-16 00:17 <a href="http://www.blogjava.net/stevenjohn/archive/2012/08/16/385559.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HTTPS</title><link>http://www.blogjava.net/stevenjohn/archive/2012/08/15/385558.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Wed, 15 Aug 2012 15:43:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/08/15/385558.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/385558.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/08/15/385558.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/385558.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/385558.html</trackback:ping><description><![CDATA[<!--StartFragment -->

<div><img src="file:///D:/SystemFile/QQrecord/331935354/Image/Image1/MZ9V4[[ZU7FDGE%60E8A3)53L.jpg"  alt="" />&nbsp;<br />京-pk发型不乱CEO&lt;<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#119;&#117;&#114;&#97;&#111;&#108;&#111;&#110;&#103;&#64;&#49;&#50;&#54;&#46;&#99;&#111;&#109;">wuraolong@126.com</a>&gt;&nbsp; 23:33:00<br />&nbsp; public String executeHttpRequest(String url, String requestContent,Log log) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Log logHttp= log;&nbsp; //logHttp对应的可能是开放平台、酒店开放平台、酒店<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpClient client = new HttpClient();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PostMethod postMethod = new PostMethod(url);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; postMethod.setRequestEntity(new StringRequestEntity(requestContent, "text/xml; charset=" + charSet, charSet));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charSet);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, soTimeOut);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int statusCode = client.executeMethod(postMethod);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BufferedReader in = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), charSet));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; StringBuffer sb = new StringBuffer();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String line;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while ((line = in.readLine()) != null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sb.append(line);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; in.close();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (statusCode != HttpStatus.SC_OK) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logHttp.error("Method:HttpClientUtil.executeHttpRequest----&gt;请求返回状态不为200,url:" + url + ",返回结果:" + sb.toString());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return "";<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logHttp.info("Method:HttpClientUtil.executeHttpRequest----&gt;请求返回状态为200,url:" + url + ",返回结果:" + sb.toString());<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return sb.toString();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; catch (Exception e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logHttp.error("Method:HttpClientUtil.executeHttpRequest----&gt;发生异常！请检查网络和参数", e);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; finally {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; postMethod.releaseConnection();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return null;<br />&nbsp;&nbsp;&nbsp; }<br />}</div><img src ="http://www.blogjava.net/stevenjohn/aggbug/385558.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-08-15 23:43 <a href="http://www.blogjava.net/stevenjohn/archive/2012/08/15/385558.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient  Commons-HttpClient</title><link>http://www.blogjava.net/stevenjohn/archive/2012/07/26/384052.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Thu, 26 Jul 2012 05:29:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/07/26/384052.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/384052.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/07/26/384052.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/384052.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/384052.html</trackback:ping><description><![CDATA[Commons-HttpClient下载地址：<br /><a href="http://archive.apache.org/dist/httpcomponents/commons-httpclient/binary/">http://archive.apache.org/dist/httpcomponents/commons-httpclient/binary/</a><br /><br />HttpClient&nbsp; 下载地址：<br /><a href="http://hc.apache.org/downloads.cgi">http://hc.apache.org/downloads.cgi</a><img src ="http://www.blogjava.net/stevenjohn/aggbug/384052.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-07-26 13:29 <a href="http://www.blogjava.net/stevenjohn/archive/2012/07/26/384052.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>apache httpClient 模拟post</title><link>http://www.blogjava.net/stevenjohn/archive/2012/05/29/379425.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Tue, 29 May 2012 04:28:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/05/29/379425.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/379425.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/05/29/379425.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/379425.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/379425.html</trackback:ping><description><![CDATA[<p>package org.abin.lee.file;</p>
<p>import java.io.IOException;<br />import java.util.ArrayList;<br />import java.util.List;</p>
<p>import junit.framework.TestCase;<br />import net.sf.json.JSONObject;</p>
<p>import org.apache.http.HttpEntity;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.NameValuePair;<br />import org.apache.http.client.ClientProtocolException;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.message.BasicNameValuePair;<br />import org.apache.http.protocol.HTTP;<br />import org.apache.http.util.EntityUtils;</p>
<p>public class QueryCustomerManagerTestCase extends TestCase {<br />&nbsp;<br />&nbsp;private static final String jsonServerUrl = "<a href="http://10.10.10.10:1010/portal/mobile/">http://10.10.10.10:1010/portal/mobile/</a>";<br />&nbsp;<br />&nbsp;static DefaultHttpClient client = new DefaultHttpClient();</p>
<p>&nbsp;public static String sendReq(String method, String jsonReq)<br />&nbsp;&nbsp;&nbsp;throws ClientProtocolException, IOException {<br />&nbsp;&nbsp;HttpPost post = new HttpPost(jsonServerUrl + method);<br />&nbsp;&nbsp;List&lt;NameValuePair&gt; nvps = new ArrayList&lt;NameValuePair&gt;();<br />&nbsp;&nbsp;nvps.add(new BasicNameValuePair("json", jsonReq));</p>
<p>&nbsp;&nbsp;post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));</p>
<p>&nbsp;&nbsp;HttpResponse response = client.execute(post);<br />&nbsp;&nbsp;HttpEntity entity = response.getEntity();<br />&nbsp;&nbsp;String entityStr = EntityUtils.toString(entity);</p>
<p>&nbsp;&nbsp;return entityStr;<br />&nbsp;}</p>
<p>&nbsp;/**<br />&nbsp; * 查询产品客户经理接口<br />&nbsp; */<br />&nbsp;public void testQueryCustomerManager() throws ClientProtocolException,<br />&nbsp;&nbsp;&nbsp;IOException {<br />&nbsp;&nbsp;String jsonReq = "{" + "RequestID:'11111',"+ "ProductID:'SC9904348'," + "timestamp:'20120416121200',"<br />&nbsp;&nbsp;&nbsp;&nbsp;+ "Hashcode:'1324546asdfgfhr65432wsdfgt654eds'" + "}";</p>
<p>&nbsp;&nbsp;String resStr = this.sendReq("query-customer-manager-json!queryCustomerManager.action", jsonReq);</p>
<p>&nbsp;&nbsp;System.out.println(resStr);</p>
<p>&nbsp;&nbsp;assertNotNull(resStr);<br />//&nbsp;&nbsp;JSONObject json = JSONObject.fromObject(resStr);<br />//&nbsp;&nbsp;assertNotNull(json.get("requestID"));<br />&nbsp;}</p>
<p>}</p><img src ="http://www.blogjava.net/stevenjohn/aggbug/379425.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-05-29 12:28 <a href="http://www.blogjava.net/stevenjohn/archive/2012/05/29/379425.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpClient post 上传文件 笔记</title><link>http://www.blogjava.net/stevenjohn/archive/2012/05/28/379369.html</link><dc:creator>abin</dc:creator><author>abin</author><pubDate>Mon, 28 May 2012 08:59:00 GMT</pubDate><guid>http://www.blogjava.net/stevenjohn/archive/2012/05/28/379369.html</guid><wfw:comment>http://www.blogjava.net/stevenjohn/comments/379369.html</wfw:comment><comments>http://www.blogjava.net/stevenjohn/archive/2012/05/28/379369.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/stevenjohn/comments/commentRss/379369.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/stevenjohn/services/trackbacks/379369.html</trackback:ping><description><![CDATA[<span style="text-align: left; widows: 2; text-transform: none; background-color: rgb(255,255,255); text-indent: 0px; font: 14px/26px Arial; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(51,51,51); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px" class="Apple-style-span">// 上传一般的参数<br />&nbsp;&nbsp; &nbsp; public static String TestParam() throws HttpException, IOException {<br />&nbsp;&nbsp; &nbsp; String url = "http://localhost:8080/IphoneTest/rece.do?method=receive";<br />&nbsp;&nbsp; &nbsp; HttpClient client = new HttpClient();<br />&nbsp;&nbsp; &nbsp; PostMethod postMethod = new PostMethod(url);<br />&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp; // 填入各个表单域的值<br />&nbsp;&nbsp; &nbsp; NameValuePair[] data = { new NameValuePair("username", "username"),<br />&nbsp;&nbsp; &nbsp; new NameValuePair("passwd", "123456") };<br />&nbsp;&nbsp; &nbsp; // 将表单的值放入postMethod中<br />&nbsp;&nbsp; &nbsp; postMethod.setRequestBody(data);<br />&nbsp;&nbsp; &nbsp; // 执行postMethod<br />&nbsp;&nbsp; &nbsp; int status = client.executeMethod(postMethod);<br />&nbsp;&nbsp; &nbsp; System.out.println(status + "--------状态------------");<br />&nbsp;&nbsp; &nbsp; if (status!= HttpStatus.SC_OK) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("--------fail-------");<br />&nbsp;&nbsp; &nbsp; } else if (status== HttpStatus.SC_OK) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String str=postMethod.getResponseBodyAsString();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("---------服务器返回值---------:"+str);<br />&nbsp;&nbsp; &nbsp; }<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; return null;<br />
<p>&nbsp;&nbsp; &nbsp; }</p>
<p><br /></p>
<p>//上传带附件的参数：</p>
<p>public static String ParamFile() {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String path = "D:\\KuGou\\b.txt";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;File file = new File(path);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (!file.exists()) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return "文件不存在!";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String url = "http://localhost:8080/IphoneTest/rece.do?method=receive";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;PostMethod filePost = new PostMethod(url);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;try {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//FilePart：用来上传文件的类<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;FilePart fp = new FilePart("file", file); //Part：类专门用来上传文件，其子类&nbsp; ，FilePart：用来上传文件的类&nbsp;&nbsp;&nbsp;&nbsp; StringPart:普通的文本参数<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println("---" + fp);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;fp.setContentType(MIME.getMIME(file.getName().substring(file.getName().lastIndexOf(".")+1)));<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//StringPart:普通的文本参数<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;StringPart uname=new StringPart("username", "aa");&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;StringPart pass=new StringPart("password", "123456");<span class="Apple-converted-space">&nbsp;</span><br /><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Part[] parts = {uname,pass,fp};<span class="Apple-converted-space">&nbsp;</span><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //对于MIME类型的请求，httpclient建议全用MulitPartRequestEntity进行包装<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;MultipartRequestEntity mre=new MultipartRequestEntity(parts,filePost.getParams());<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;filePost.setRequestEntity(mre);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;HttpClient client = new HttpClient();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;int status = client.executeMethod(filePost);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println(status + "--------------");<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (status != HttpStatus.SC_OK) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println(status + "--------------fail----");<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;} else if (status == HttpStatus.SC_OK) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String str = "";&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span class="Apple-converted-space">&nbsp;</span><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;str = filePost.getResponseBodyAsString();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println(filePost.getResponseBodyAsString()+ "---------服务器返回值---------");<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br /><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;} catch (Exception e) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;e.printStackTrace();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return null;<br />&nbsp;&nbsp; &nbsp;}</p>
<p><br /></p>
<p>//同时上传几个附近</p>
<p>public static String ParamFiles() {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String path = "D:\\KuGou\\b.txt";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String path2 = "D:\\KuGou\\a.txt";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;File file = new File(path);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;File file2=new File(path2);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (!file.exists()) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return "文件不存在!";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (!file2.exists()) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return "文件不存在!";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String url = "http://localhost:8080/IphoneTest/rece.do?method=receive";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;PostMethod filePost = new PostMethod(url);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;try {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//FilePart：用来上传文件的类<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;FilePart fp = new FilePart("file", file); //Part：类专门用来上传文件，其子类&nbsp; ，FilePart：用来上传文件的类&nbsp;&nbsp;&nbsp;&nbsp; StringPart:普通的文本参数<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;FilePart fp2=new FilePart("file2", file2);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println("---" + fp);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;fp.setContentType(MIME.getMIME(file.getName().substring(file.getName().lastIndexOf(".")+1)));<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//StringPart:普通的文本参数<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;StringPart uname=new StringPart("username", "aa");&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;StringPart pass=new StringPart("password", "123456");<span class="Apple-converted-space">&nbsp;</span><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Part[] parts = {uname,pass,fp,fp2};<span class="Apple-converted-space">&nbsp;</span><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;MultipartRequestEntity mre=new MultipartRequestEntity(parts,filePost.getParams());<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;filePost.setRequestEntity(mre);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;HttpClient client = new HttpClient();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;int status = client.executeMethod(filePost);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println(status + "--------------");<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (status != HttpStatus.SC_OK) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println(status + "--------------fail----");<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;} else if (status == HttpStatus.SC_OK) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String str = "";<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;str = filePost.getResponseBodyAsString();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println(filePost.getResponseBodyAsString()+ "---------服务器返回值---------");<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br /><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;} catch (Exception e) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;e.printStackTrace();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return null;<br />&nbsp;&nbsp; &nbsp;}</p>
<p><br /></p>
<p>测试：</p>
<p>public static void main(String[] args) throws HttpException, IOException {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;// 上传一般的参数<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; TestParam();<br /><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; ParamFile();<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;ParamFiles();<br />&nbsp;&nbsp; &nbsp;<br />&nbsp;&nbsp; &nbsp;}<br /></p>
<p><br /></p></span><br class="Apple-interchange-newline" /> <img src ="http://www.blogjava.net/stevenjohn/aggbug/379369.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/stevenjohn/" target="_blank">abin</a> 2012-05-28 16:59 <a href="http://www.blogjava.net/stevenjohn/archive/2012/05/28/379369.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>