HttpClient是 Apache Jakarta Common下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,本文采用的HttpClient版本是4.4.1 许多需要后台模拟请求的系统或者框架都用的是httpclient。所以作为一个java开发人员,有必要学一学。本文提供了一个简单的demo,供初学者参考。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:创建CloseableHttpClient对象。 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容; 调用CloseableHttpResponse 的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。 释放连接。无论执行方法是否成功,都必须释放连接 下面是一个POST带参数请求的例子,访问天气网站,用到的HttpClient版本是4.4.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 public static String send (String url, Map<String, String> map, String encoding) throws IOException { String body = "" ; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); List<NameValuePair> nvp = new ArrayList<>(); if (map !=null ){ for (Entry<String, String> entry : map.entrySet()) { nvp.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } post.setEntity(new UrlEncodedFormEntity(nvp,encoding)); System.out.println("请求地址:----" +url); System.out.println("请求参数:-----" +nvp.toString()); post.setHeader("Content-type" , "application/x-www-form-urlencoded" ); post.setHeader("User-Agent" , "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)" ); CloseableHttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); if (entity!=null ){ System.out.println("entity----" +entity); body = EntityUtils.toString(entity, encoding); } response.close(); return body; }
测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public static void main (String[] args) throws IOException { String url="http://php.weather.sina.com.cn/iframe/index/w_cl.php" ; Map<String, String> map = new HashMap<String, String>(); map.put("code" , "js" ); map.put("day" , "0" ); map.put("city" , "武汉" ); map.put("dfc" , "1" ); map.put("charset" , "utf-8" ); String body = send(url1, map,"utf-8" ); System.out.println("交易响应结果:" ); System.out.println(body); System.out.println("-----------------------------------" ); map.put("city" , "北京" ); body = send(url, map, "utf-8" ); System.out.println("交易响应结果:" ); System.out.println(body); }
结果 1 2 3 4 5 6 7 8 请求地址:----http://php.weather.sina.com.cn/iframe/index/w_cl.php 请求参数:-----[dfc=1, charset=utf-8, code=js, city=武汉, day=0] entity----org.apache.http.client.entity.DecompressingEntity@548e7350 交易响应结果: (function(){var w=[];w['武汉']=[{s1:'晴',s2:'晴',f1:'qing',f2:'qing',t1:'28',t2:'20',p1:'≤3',p2:'≤3',d1:'无持续风向',d2:'无持续风向'}];var add={now:'2017-09-11 20:14:23',time:'1505132063',update:'北京时间09月11日17:10更新',error:'0',total:'1'};window.SWther={w:w,add:add};})();//0
注意,静态文件不接受post请求 Apache、IIS、Nginx等绝大多数web服务器,都不允许静态文件响应POST请求,否则会返回HTTP/1.1 405 Method not allowed错误。
解决方法,修改nginx配置 1 2 3 4 5 location ^~ /m/coupon { root /data/server/h5.weidian.com; error_page 405 =200 https://$host$request_uri; }
附各种请求的写法 1.GET请求 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 public class DoGET { public static void main (String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://www.baidu.com/" ); CloseableHttpResponse response = null ; try { response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200 ) { String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println("内容长度:" + content.length()); } } finally { if (response != null ) { response.close(); } httpclient.close(); } } }
2.带参数的GET请求 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 public class DoGETParam { public static void main (String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder("http://www.baidu.com/s" ).setParameter("wd" , "java" ).build(); System.out.println(uri); HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = null ; try { response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200 ) { String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println(content); } } finally { if (response != null ) { response.close(); } httpclient.close(); } } }
3.POST请求 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 public class DoPOST { public static void main (String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.oschina.net/" ); CloseableHttpResponse response = null ; try { response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200 ) { String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println(content); } } finally { if (response != null ) { response.close(); } httpclient.close(); } } }
4.带参数的POST请求 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 public class DoPOSTParam { public static void main (String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.oschina.net/search" ); List<NameValuePair> parameters = new ArrayList<NameValuePair>(0 ); parameters.add(new BasicNameValuePair("scope" , "project" )); parameters.add(new BasicNameValuePair("q" , "java" )); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); httpPost.setEntity(formEntity); CloseableHttpResponse response = null ; try { response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200 ) { String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println(content); } } finally { if (response != null ) { response.close(); } httpclient.close(); } } }
原文链接: https://www.317318.xyz/p/e103ddbe.html
版权声明: 转载请注明出处.