使用HttpClient模拟POST请求

       HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。当前官网最新版介绍页是:http://hc.apache.org/httpcomponents-client-4.5.x/index.html


       许多需要后台模拟请求的系统或者框架都用的是httpclient。所以作为一个java开发人员,有必要学一学。本文提供了一个简单的demo,供初学者参考。


       使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

    1. 创建CloseableHttpClient对象。
    2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
    3. 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
    4. 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
    5. 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
    6. 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
    7. 释放连接。无论执行方法是否成功,都必须释放连接

       具体代码如下(HttpClient-4.4.1):

[java]  view plain  copy
  1. /**  
  2.  * 简单httpclient实例 
  3.  *  
  4.  * @author arron 
  5.  * @date 2015年11月11日 下午6:36:49  
  6.  * @version 1.0  
  7.  */  
  8. public class SimpleHttpClientDemo {  
  9.   
  10.     /** 
  11.      * 模拟请求 
  12.      *  
  13.      * @param url       资源地址 
  14.      * @param map   参数列表 
  15.      * @param encoding  编码 
  16.      * @return 
  17.      * @throws ParseException 
  18.      * @throws IOException 
  19.      */  
  20.     public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{  
  21.         String body = "";  
  22.   
  23.         //创建httpclient对象  
  24.         CloseableHttpClient client = HttpClients.createDefault();  
  25.         //创建post方式请求对象  
  26.         HttpPost httpPost = new HttpPost(url);  
  27.           
  28.         //装填参数  
  29.         List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
  30.         if(map!=null){  
  31.             for (Entry<String, String> entry : map.entrySet()) {  
  32.                 nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  33.             }  
  34.         }  
  35.         //设置参数到请求对象中  
  36.         httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));  
  37.   
  38.         System.out.println("请求地址:"+url);  
  39.         System.out.println("请求参数:"+nvps.toString());  
  40.           
  41.         //设置header信息  
  42.         //指定报文头【Content-type】、【User-Agent】  
  43.         httpPost.setHeader("Content-type""application/x-www-form-urlencoded");  
  44.         httpPost.setHeader("User-Agent""Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  45.           
  46.         //执行请求操作,并拿到结果(同步阻塞)  
  47.         CloseableHttpResponse response = client.execute(httpPost);  
  48.         //获取结果实体  
  49.         HttpEntity entity = response.getEntity();  
  50.         if (entity != null) {  
  51.             //按指定编码转换结果实体为String类型  
  52.             body = EntityUtils.toString(entity, encoding);  
  53.         }  
  54.         EntityUtils.consume(entity);  
  55.         //释放链接  
  56.         response.close();  
  57.         return body;  
  58.     }  
  59. }  

       在main方法中测试一下:

[java]  view plain  copy
  1. public static void main(String[] args) throws ParseException, IOException {  
  2.     String url="http://php.weather.sina.com.cn/iframe/index/w_cl.php";  
  3.     Map<String, String> map = new HashMap<String, String>();  
  4.     map.put("code""js");  
  5.     map.put("day""0");  
  6.     map.put("city""上海");  
  7.     map.put("dfc""1");  
  8.     map.put("charset""utf-8");  
  9.     String body = send(url, map,"utf-8");  
  10.     System.out.println("交易响应结果:");  
  11.     System.out.println(body);  
  12.   
  13.     System.out.println("-----------------------------------");  
  14.   
  15.     map.put("city""北京");  
  16.     body = send(url, map, "utf-8");  
  17.     System.out.println("交易响应结果:");  
  18.     System.out.println(body);  
  19. }  
       结果如下:
[html]  view plain  copy
  1. 请求地址:http://php.weather.sina.com.cn/iframe/index/w_cl.php  
  2. 请求参数:[dfc=1charset=utf-8, day=0code=jscity=上海]  
  3. 交易响应结果:  
  4. (function(){var w=[];w['上海']=[{s1:'小雨',s2:'小雨',f1:'xiaoyu',f2:'xiaoyu',t1:'21',t2:'16',p1:'≤3',p2:'≤3',d1:'南风',d2:'北风'}];var add={now:'2015-11-16 13:16:23',time:'1447650983',update:'北京时间11月16日08:10更新',error:'0',total:'1'};window.SWther={w:w,add:add};})();//0  
  5.   
  6. -----------------------------------  
  7. 请求地址:http://php.weather.sina.com.cn/iframe/index/w_cl.php  
  8. 请求参数:[dfc=1charset=utf-8, day=0code=jscity=北京]  
  9. 交易响应结果:  
  10. (function(){var w=[];w['北京']=[{s1:'多云',s2:'多云',f1:'duoyun',f2:'duoyun',t1:'9',t2:'1',p1:'≤3',p2:'≤3',d1:'无持续风向',d2:'无持续风向'}];var add={now:'2015-11-16 13:18:35',time:'1447651115',update:'北京时间11月16日08:10更新',error:'0',total:'1'};window.SWther={w:w,add:add};})();//0  

       现在我们测试一下https链接:https://www.qingyidai.com/investmanagement/invest.shtml

[java]  view plain  copy
  1. public static void main(String[] args) throws ParseException, IOException {  
  2.     String url = "https://www.qingyidai.com/investmanagement/invest.shtml";  
  3.     String body = send(url, null"utf-8");  
  4.     System.out.println("交易响应结果:");  
  5.     System.out.println(body);  
  6. }  
       结果发现,居然正常拿到结果了:


       原来如果网站的证书已经被ca机构认证通过了,那么用HttpClient来调用的话,会直接成功的。不用再单独配置htts链接了。不过如果是自签名的证书,还是需要配置https的


转自: http://blog.csdn.net/xiaoxian8023/article/details/49863967


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值