首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >httpcomponents 4.5.2 简单使用

httpcomponents 4.5.2 简单使用

作者头像
王念博客
发布2019-07-25 17:45:14
1.3K0
发布2019-07-25 17:45:14
举报
文章被收录于专栏:王念博客王念博客

HttpComponents 也就是以前的httpclient项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端/服务器编程工具包,并且它支持 HTTP 协议最新的版本和建议。不过现在的 HttpComponents 包含多个子项目,有:

  • HttpComponents Core
  • HttpComponents Client
  • HttpComponents AsyncClient
  • Commons HttpClient

以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。

  • 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  • 支持自动转向
  • 支持 HTTPS 协议
  • 支持代理服务器等
  • 支持Cookie

之前用的HttpClient的方法都失效了,比如 httpclinet =new DefaultHttpClient(); 不知道为啥包里80%的类都失效了,总是觉得创建一个httpclient实例会比较麻烦,记不住。所以整理了一下新的方式简单使用。

简单使用

导入jar包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

get请求获取响应

CloseableHttpClient httpClient= HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = httpClient.execute(httpget);
HttpEntity httpEntity= response.getEntity();
String strResult= EntityUtils.toString(httpEntity);

post请求获取响应

HttpPost httpost = new HttpPost("https://www.baidu.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

HttpClient提供URIBuilder工具类来简化URIs的创建和修改过程。

URI uri = new URIBuilder()  
        .setScheme("http")  
        .setHost("www.google.com")  
        .setPath("/search")  
        .setParameter("q", "httpclient")  
        .setParameter("btnG", "Google Search")  
        .setParameter("aq", "f")  
        .setParameter("oq", "")  
        .build();  
HttpGet httpget = new HttpGet(uri);  
System.out.println(httpget.getURI())

模拟浏览器请求

httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档