轻松把玩HttpClient之模拟post请求示例

阳光穿透心脏的1/2处 2022-05-14 16:09 308阅读 0赞

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

许多需要后台模拟请求的系统或者框架都用的是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)等方法可获取服务器的响应头。
释放连接。无论执行方法是否成功,都必须释放连接

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

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

在main方法中测试一下:

  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. System.out.println("-----------------------------------");
  13. map.put("city", "北京");
  14. body = send(url, map, "utf-8");
  15. System.out.println("交易响应结果:");
  16. System.out.println(body);
  17. }

结果如下:

  1. 请求地址:http://php.weather.sina.com.cn/iframe/index/w_cl.php
  2. 请求参数:[dfc=1, charset=utf-8, day=0, code=js, city=上海]
  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

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

  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. }

结果发现,居然正常拿到结果了:

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

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读