HttpClient
Posted 功不唐捐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient相关的知识,希望对你有一定的参考价值。
https://www.ibm.com/developerworks/cn/opensource/os-httpclient/
IBM这篇讲解的比较规范、清晰。
http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html
http://blog.csdn.net/wangpeng047/article/details/19624529
这两篇给出了HttpClient的各种应用。
HttpClient 4.3的变化较大,譬如getMethod/postMethod用HttpGet/HttpPost取代。
旧版
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 }
新版
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 }
以上是关于HttpClient的主要内容,如果未能解决你的问题,请参考以下文章
HttpClient学习--HttpClient的POST请求过程源码解读
java用httpclient 执行到httpclient.execute(request); 这句代码假死不往下执行不报错