https://www.ibm.com/developerworks/cn/opensource/os-httpclient/html
IBM這篇講解的比較規範、清晰。java
http://www.blogjava.net/Alpha/archive/2007/01/22/95216.htmljson
http://blog.csdn.net/wangpeng047/article/details/19624529app
這兩篇給出了HttpClient的各類應用。post
HttpClient 4.3的變化較大,譬如getMethod/postMethod用HttpGet/HttpPost取代。url
舊版.net
1 public class HttpTests { 2 /** 3 * @param args 4 * @throws Exception 5 */ 6 public static void main(String[] args) throws Exception { 7 HttpClient httpclient = new HttpClient(); 8 PostMethod httpPost =new PostMethod("******/abc"); 9 NameValuePair[] param = { new NameValuePair("username", "vip")}; 10 httpPost.setRequestBody(param); 11 httpclient.executeMethod(httpPost); 12 } 13 }
新版 code
1 public static String getMes(String url, String params) { 2 CloseableHttpClient client = HttpClients.createDefault(); 3 HttpPost htPost = new HttpPost(url); 4 String backMes = null; 5 try { 6 htPost.setHeader("content-type", "application/json"); 7 StringEntity reqEntity = new StringEntity(params); 8 htPost.setEntity(reqEntity); 9 HttpResponse httpResponse = client.execute(htPost); 10 HttpEntity entity = httpResponse.getEntity(); 11 backMes = EntityUtils.toString(entity, "UTF-8").toString(); 12 } catch (ClientProtocolException e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } catch (IOException e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } finally { 19 try { 20 client.close(); 21 client = null; 22 } catch (IOException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 return backMes; 28 }