HttpClient介绍 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
下载和安装
下载地址http://hc.apache.org/downloads.cgi
下载二进制文件后解压lib文件夹,将jar包复制粘贴到项目目录,右击add to Build Path. 关联源码到httpcomponents-asyncclient-4.1.1-src\httpcomponents-asyncclient-4.1.1\目录即可查看源码。
使用示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 public static void post () { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost( "http://localhost:8080/服务端/servlet/Login" ); List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); formparams.add(new BasicNameValuePair("user" , "lisi" )); formparams.add(new BasicNameValuePair("pwd" , "123456" )); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8" ); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null ) { Header[] allHeaders = response.getAllHeaders(); for (Header h : allHeaders) { System.out .println(h.getName() + " : " + h.getValue()); } System.out .println("--------------------------------------" ); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8" )); System.out .println("--------------------------------------" ); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }