原文链接: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. 【python 爬虫】fake-useragent Maximum amount of retries reached解决方案

    前言 在用fake-useragent的时候发生报错,fake_useragent.errors.FakeUserAgentError: Maximum amount of retries reach ...

  2. WordPress 安全配置

    关闭后台主题编辑功能 WordPress后台的主题一旦权限开放就可以在后台直接编辑,如果没有开放则只可浏览.主机若有安装suPHP默认就是可以编辑.如果你觉得这项功能用不到,建议您可以关闭它,毕竟直接 ...

  3. 有点干货 | Jdk1.8新特性实战篇(41个案例)

    作者:小傅哥 博客:https://bugstack.cn - 汇总系列原创专题文章 沉淀.分享.成长,让自己和他人都能有所收获!

  4. Java基础语法--分支结构

    if-else 结构 if(条件表达式){ 执行代码块; } if(条件表达式){ 执行代码块; }else { 执行代码块; } if(条件表达式){ 执行代码块; }else if (条件表达式) ...

  5. Spring_AOP_AspectJ支持的通知注解

    1.AOP前奏: 使用动态代理解决日志需求 ArithmeticCalculator.java package com.aff.spring.aop.helloworld; public interf ...

  6. 分布式项目开发-springmvc.xmll基础配置

    基础步骤: 1 包扫描 2 驱动开发 3 视图解析器 4 文件上传解析器 5 拦截器 6 静态资源 <beans xmlns="http://www.springframework.o ...

  7. php实现ajax请求的方法

    php实现ajax请求的方法 Ajax页面:第一,了解底层逻辑,正是平常的1个提交在无刷新的条件下发出请求后完成回应,之后去针对你需要的条件来做动作. <!DOCTYPE html> &l ...

  8. Rocket - debug - TLDebugModuleInner - Abstract Command Decoding & Generation

    https://mp.weixin.qq.com/s/0zKSTktxgzo5uCUphqaWSQ 介绍抽象命令的解码和生成. 1. accessRegisterCommandReg accessRe ...

  9. 高性能可扩展mysql 笔记(三)Hash分区、RANGE分区、LIST分区

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.MySQL分区表操作 1.定义:数据库表分区是数据库基本设计规范之一,分区表在物理上表现为多个文件, ...

  10. JAVA-蓝桥杯-算法训练-字符串变换

    问题描述 相信经过这个学期的编程训练,大家对于字符串的操作已经掌握的相当熟练了.今天,徐老师想测试一下大家对于字符串操作的掌握情况.徐老师自己定义了1,2,3,4,5这5个参数分别指代不同的5种字符串 ...