原文链接:https://blog.csdn.net/justry_deng/article/details/81042379

HttpClient的主要功能:

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

引入依赖:

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

get无参:

    /**
* GET---无参测试
*
* @date 2018年7月13日 下午4:18:50
*/
@Test
public void doGetTestOne() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Get请求
HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerOne"); // 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

GET有参(方式一:直接拼接URL):

    /**
* GET---有参测试 (方式一:手动在url后面加上参数)
*
* @date 2018年7月13日 下午4:19:23
*/
@Test
public void doGetTestWayOne() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数
StringBuffer params = new StringBuffer();
try {
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name=" + URLEncoder.encode("&", "utf-8"));
params.append("&");
params.append("age=24");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} // 创建Get请求
HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
// 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet); // 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

GET有参(方式二:使用URI获得HttpGet):

    /**
* GET---有参测试 (方式二:将参数放入键值对类中,再放入URI中,从而通过URI得到HttpGet实例)
*
* @date 2018年7月13日 下午4:19:23
*/
@Test
public void doGetTestWayTwo() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数
URI uri = null;
try {
// 将参数放入键值对类NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", "&"));
params.add(new BasicNameValuePair("age", "18"));
// 设置uri信息,并将参数集合放入uri;
// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
uri = new URIBuilder().setScheme("http").setHost("localhost")
.setPort(12345).setPath("/doGetControllerTwo")
.setParameters(params).build();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
// 创建Get请求
HttpGet httpGet = new HttpGet(uri); // 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet); // 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

  

  

(一)HttpClient Get请求的更多相关文章

  1. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

  2. Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求

    HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 jav ...

  3. 使用HttpClient发送请求接收响应

    1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...

  4. 使用httpclient post请求中文乱码解决办法

    使用httpclient post请求中文乱码解决办法   在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码 ...

  5. java HttpClient POST请求

    一个简单的HttpClient POST 请求实例 package com.httpclientget; import java.awt.List; import java.util.ArrayLis ...

  6. java HttpClient GET请求

    HttpClient GET请求小实例,先简单记录下. package com.httpclientget; import java.io.IOException; import org.apache ...

  7. HttpClient get和HttpClient Post请求的方式获取服务器的返回数据

    1.转自:https://blog.csdn.net/alinshen/article/details/78221567?utm_source=blogxgwz4 /*  * 演示通过HttpClie ...

  8. 给HttpClient添加请求头(HttpClientFactory)

    前言 在微服务的大环境下,会出现这个服务调用这个接口,那个接口的情况.假设出了问题,需要排查的时候,我们要怎么关联不同服务之间的调用情况呢?换句话就是说,这个请求的结果不对,看看是那里出了问题. 最简 ...

  9. HttpClient get请求获取数据流

    HttpClient get请求获取数据流,将数据保存为文件 public String getStreamFile(String url) throws Exception { HttpClient ...

  10. httpclient: 设置请求的超时时间,连接超时时间等

    httpclient: 设置请求的超时时间,连接超时时间等 public static void main(String[] args) throws Exception{ //创建httpclien ...

随机推荐

  1. 避免scrollview内部控件输入时被键盘遮挡,监听键盘弹起,配合做滚动

    1,监听键盘 2,根据当前键盘弹起高度与控件的底部位置计算滑动距离 3,根据滑动距离在键盘弹起和隐藏是分别设置动画完成滑动     实现: 1,监听键盘使用   #pragma mark - 键盘监听 ...

  2. poj2699 转化为可行性判定问题+二分枚举+最大流

    The Maximum Number of Strong Kings Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2302 ...

  3. 10个典型的JavaScript面试题

    问题1:作用域 考虑如下代码:   JavaScript   1 2 3 4 5 6 7 (function() {   var a = b = 5;   })();   console.log(b) ...

  4. Gunicorn+Nginx+Flask项目部署

    安装python3.6 1)前往用户根目录 >: cd ~ 2)下载 或 上传 Python3.6.7 >: wget https://www.python.org/ftp/python/ ...

  5. shiro认证通过之后的授权

    subject.hasRole("") ; subject.hasRoles(List); subject.hasAllRoles(); subject.isPermitted(& ...

  6. linux 权限笔记

    权限模型 linux权限模型,指的是对文件.文件夹同的读写权限,同用户之间的权限管理模型 三种角色 user 文件.文件夹的创建者,所有人 group 一个group对应多个user,user自动具有 ...

  7. 关于如何查看论文是否被SCI或者EI收录

    最好的方法,在高校图书馆网站上进行查询. 另外还有就是去对应网站查询: SCI:https://apps.webofknowledge.com/UA_GeneralSearch_input.do?pr ...

  8. [Android-NDK编译] ndk 编译 c++ 兼容性问题汇总整理

    1.__int64找不到符号 采用int64_t来代替: #if defined(__ANDROID__) typedef int64_t __int64; #endif 2.<sys/io.h ...

  9. [PHP自动化-进阶]001.CURL模拟登录并采集数据

    引言:PHP可以通过libcurl实现模拟登录,提交数据,违法乱纪,烧杀抢虐等等事项. 简单说明一下"libcurl",补一下脑: libcurl目前支持http.https.ft ...

  10. 【转】动态规划:最长递增子序列Longest Increasing Subsequence

    转自:https://www.cnblogs.com/coffy/p/5878915.html 设f(i)表示L中以ai为末元素的最长递增子序列的长度.则有如下的递推方程: 这个递推方程的意思是,在求 ...