HttpClient4.x工具可以让我们输入url,就可以请求某个页面(个人感觉挺实用的,特别是封装在代码中)

首先我们需要在maven工程中添加依赖

<dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.2</version>
            </dependency>
 
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.1.1</version>
            </dependency>
                    <dependency>
                    <groupId>org.apache.httpcomponents</groupId>
                    <artifactId>httpcore</artifactId>
            </dependency>
 
 
        <!-- gson工具,封装http的时候使用 -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
 
接下来,我们来封装一下,有get/post请求
 /**
* 封装http get post
*/
public class HttpUtils { private static final Gson gson = new Gson();
/**
* get方法
*/
public static Map<String,Object> doget(String url,int timeout){
Map<String,Object> map = new HashMap<>();
CloseableHttpClient httpClient = HttpClients.createDefault();
  //配置可有可无,根据个人情景
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) //设置连接超时时间
.setConnectionRequestTimeout(timeout) //设置请求超时时间
.setSocketTimeout(timeout)
.setRedirectsEnabled(true) //设置允许自动重定向
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig); try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
String jsonResult = EntityUtils.toString(httpResponse.getEntity());
map = gson.fromJson(jsonResult, map.getClass()); //通过gson工具,将响应流转换成map集合
} }catch(Exception e){
e.printStackTrace();
}finally{
try{
httpClient.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return map;
}
/**
* 封装post,与get有异曲同工之妙
*/
public static String dopost(String url,String data,int timeout){
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) //设置连接超时
.setConnectionRequestTimeout(timeout) //设置请求超时
.setRedirectsEnabled(true) //设置允许自动重定向
.build(); HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type","text/html; chartset=UTF-8"); //添加头信息
if (data != null && data instanceof String) {//使用字符串传参
StringEntity stringEntity = new StringEntity(data, "UTF-8");
httpPost.setEntity(stringEntity);
}
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpResponse.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(httpEntity);
return result;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
httpClient.close();
}catch (Exception e){
e.printStackTrace();
}
} return null; }
}

封装好HttpClient工具后,我们来调用一下

get请求

HttpUtils.doget(请求地址,请求时间(timeout));

post请求

HttpUtils.dopost(请求地址, 请求传的数据(传之前需要转换成string), 请求时间(timeout));

HttpClient4.x工具获取如何使用的更多相关文章

  1. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_5-5.HttpClient4.x工具获取使用

    笔记 5.HttpClient4.x工具获取使用     简介:讲解httpClient4.x相关依赖,并封装基本方法. 1.加入依赖         <dependency>       ...

  2. 微信开发者工具获取位置错误(定位到北京)---调用wx.getLocation不出现获取定位提示

    微信开发者工具获取不到自己当前的位置可能是以下几个原因: 1.调用wx.getLocation方法之后需要在app.json中声明permission字段 { "pages": [ ...

  3. httpclient4.3 工具类

    httpclient4.3  java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...

  4. Chrome浏览器获取XPATH的方法----通过开发者工具获取

    chrome有自己的开发者工具,可以用这儿来直接获取xpath,都不用担心正确性了. 具体使用步骤如下: 1.在chrome浏览器的右上角有个选择菜单,也就是这个,点一下: 2.在列表最后面有个“更多 ...

  5. 微信小程序开发着工具获取和更新newticket

    newticket是微信开发者工具和微信后台交互的凭证.大多数工具的操作都是需要newticket. 如何获取newticket? 打开开发者工具,依次点击菜单设置->通用设置->代理,使 ...

  6. ADB工具 获取ROOT权限及复制文件方法

    adb push d:\tm3_sqlit.db data/zouhao/tm3_sqlit.dbadb pull data/zouhao/tm3_sqlit.db d:\tm3_sqlit.db a ...

  7. 利用Windows7自带的截图工具获取菜单截图的步骤

    打开截图工具后,按 Esc,然后打开要捕获的菜单. 按 Ctrl+PrtScn. 单击“新建”按钮旁边的箭头,从列表中选择“任意格式截图”.“矩形截图”.“窗口截图”或“全屏幕截图”,然后选择要捕获的 ...

  8. 我的Android开发之路——百度地图开源工具获取定位信息

    定位技术在现在的移动设备上是必不可少的,许多app都会使用定位功能. 通常定位方式有两种:GPS定位:网络定位. Android系统对这两种定位方式都提供了相应的API支持,但是因为google的网络 ...

  9. Linux下通过tcpdump抓包工具获取信息

    介绍 tcpdump是网络数据包截获分析工具.支持针对网络层.协议.主机.网络或端口的过滤.并提供and.or.not等逻辑语句帮助去除无用的信息. tcpdump - dump traffic on ...

随机推荐

  1. SpringAOP使用

    AspectJ 注解: 1.@Aspect.@Pointcut.Advice @Aspect @Component public class SecurityAspect { @Autowired A ...

  2. UICollectionView的基本使用 collectionView

    #pragma mark -- 创建CollectionView - (void)createCollectionView{ //关闭自适应 self.automaticallyAdjustsScro ...

  3. Ubuntu wubi.exe 安装到Windows 正在下载ubuntu-11.04-desktop-i386.iso

    下载一个Ubuntu的iso镜像,用虚拟光驱加载后,点击 wubi.exe->安装到Windows 设置好后,进入安装,又自动开始下载iso镜像了,提示:正在下载ubuntu-11.04-des ...

  4. 删除Ati显卡桌面右键菜单(配置可交换显卡,显示卡属性,图形选项,图形属性)

    Win+R 打开注册表 依次找到 HKEY_CLASSES_ROOT\Directory\Background\shellex\ContextMenuHandlers 保留Gadgets.New.Sh ...

  5. 奇偶交错排列(DFS)

    Description 一个1-n1−n的排列满足所有相邻数字奇偶性不同,那么称该排列为奇偶交错排列. 按字典序输出1-n1−n的所有奇偶交错排列. Input 输入一个整数n( 2 \le n \l ...

  6. P2905 [USACO08OPEN]农场危机Crisis on the Farm

    传送门 DP 设 f [ i ] [ j ] [ k ] 表示已经走了 i 步,向上走了 j 步,向右走了 k 步时能拯救的最多奶牛数(j,k可以为负,表示反向) 设 g [ i ] [ j ] 表示 ...

  7. hdu1387 模拟队列

    Team Queue Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Su ...

  8. Go语言基础之18--接口编程

    一.接口介绍和定义 1.1 接口定义了一个对象的行为规范 A. 只定义规范,不实现 B. 具体的对象需要实现规范的细节 葵花宝典: 接口就是一层封装,1个例子,封装一个返还浏览器内容的接口.为什么不直 ...

  9. redis实现SSO单点登录,集群,分布式锁

    https://blog.csdn.net/aussme/article/details/80660443

  10. 7.Hibernate 检索

    1.Hibernate检索方式 检索方式简介: 导航对象图检索方式:根据已经加载的对象,导航到其他对象.OID检索方式:按照对象的OID来检索对象.Session 的 get() 和 load() 方 ...