相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;
httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...
下面是测试代码(全部总结来自官方文档,以及翻译)
须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi
/** * */ private static void test26() throws ClientProtocolException, IOException{ // CloseableHttpClient httpclient = HttpClients.createDefault(); // HttpClientContext context = HttpClientContext.create(); // HttpGet httpget = new HttpGet("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo"); // CloseableHttpResponse response = httpclient.execute(httpget, context); // try { // Principal principal = context.getUserToken(Principal.class); // System.out.println(principal); // } finally { // response.close(); // } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpClientContext context1 = HttpClientContext.create(); HttpGet httpget1 = new HttpGet("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo"); CloseableHttpResponse response1 = httpclient.execute(httpget1, context1); try { HttpEntity entity1 = response1.getEntity(); } finally { response1.close(); } Principal principal = context1.getUserToken(Principal.class); HttpClientContext context2 = HttpClientContext.create(); context2.setUserToken(principal); HttpGet httpget2 = new HttpGet("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo"); CloseableHttpResponse response2 = httpclient.execute(httpget2, context2); try { HttpEntity entity2 = response2.getEntity(); } finally { response2.close(); } }
时间: 2024-11-03 12:25:26