一、什么是httpclient

  HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议
来访问网络资源;虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,
JDK 库本身提供的功能还不够丰富和灵活;HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新
的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议
下载地址:http://hc.apache.org/

二、功能介绍

 以下列出的是 HttpClient 提供的主要的功能
  (1)实现了所有 HTTP 的方法
  (2)支持自动转向
  (3)支持 HTTPS 协议
  (4)支持代理服务器等
要知道更多详细的功能可以参见 HttpClient 的主页

三、导入依赖

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>

四、用法示例

   (1)执行get请求

public class DoGET {
public static void main(String[] args) throws Exception {
//创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//创建http GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
CloseableHttpResponse response = null;
try {
//执行请求
response = httpclient.execute(httpGet);
//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("内容长度:" + content.length());
//FileUtils.writeStringToFile(new File("C:\\baidu.html"), content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}

   (2)执行带参数的get请求

public class DoGETParam {
public static void main(String[] args) throws Exception {
//创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//定义请求的参数
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
System.out.println(uri); //创建http GET请求
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
//执行请求
response = httpclient.execute(httpGet);
//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}

   (3)执行post请求

public class DoPOST {
public static void main(String[] args) throws Exception {
//创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); //创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/"); CloseableHttpResponse response = null;
try {
//执行请求
response = httpclient.execute(httpPost);
//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}

   (4)执行带参数的post请求

public class DoPOSTParam {
public static void main(String[] args) throws Exception {
//创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); //创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); //设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
//构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
//将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity); CloseableHttpResponse response = null;
try {
//执行请求
response = httpclient.execute(httpPost);
//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}

   (5)封装HttpClient通用工具类

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri); // 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} public static String doGet(String url) {
return doGet(url, null);
} public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
} public static String doPost(String url) {
return doPost(url, null);
}
}

淘淘商城之httpclient的更多相关文章

  1. 001淘淘商城项目:项目的Maven工程搭建

    开始一个新的项目,特此记录,资料全部来源于传智播客,感谢. 我们要做一个类似电商的项目.用maven做管理. maven里面主要分为三种工程: 1:pom工程:用在父级工程,聚合工程中 2:war工程 ...

  2. 淘淘商城_day01_课堂笔记

    今日大纲 聊聊电商行业 电商行业发展 11.11 2015双11: 2016年: 预测:2017年的双11交易额将达到:1400亿 电商行业技术特点 淘淘商城简介 淘淘商城的前身 电商行业的概念 B2 ...

  3. 【原】从零开始改造淘淘商城(引入dubbo解决项目耦合)02

    前言: 关于为什么要引入dubbo框架,而不是用spring cloud或者是motan呢,主要是笔者现在公司用的就是dubbo,并且第一次接触到微服务的概念是来源于dubbo,再加上最近dubbo频 ...

  4. ssm(Spring、Springmvc、Mybatis)实战之淘淘商城-第一天

    文章大纲 一.课程介绍二.淘淘商城基本介绍三.后台管理系统工程结构与搭建四.svn代码管理五.项目源码与资料下载六.参考文章   一.课程介绍 1. 课程大纲 一共14天课程(1)第一天:电商行业的背 ...

  5. JAVAEE——淘淘商城第一天:电商行业的背景和技术特点,商城的介绍、技术的选型、系统架构和工程搭建

    1. 学习计划 1.电商行业的背景. 2.电商行业的技术特点 3.商城的介绍 a) 常用的名词介绍 b) 系统功能介绍 4.淘淘商城的系统架构 a) 传统架构 b) 分布式架构 c) 基于服务的架构 ...

  6. ssm(Spring、Springmvc、Mybatis)实战之淘淘商城-第十四天(非原创)

    文章大纲 一.淘淘商城总体架构介绍二.淘淘商城重要技术点总结三.项目常见面试题四.项目学习(all)资源下载五.参考文章 一.淘淘商城总体架构介绍 1. 功能架构   2. 技术选型 (1)Sprin ...

  7. ssm(Spring、Springmvc、Mybatis)实战之淘淘商城-第六天(非原创)

    文章大纲 一.课程介绍二.今日内容简单介绍三.Httpclient介绍与实战四.项目源码与资料下载五.参考文章   一.课程介绍 一共14天课程(1)第一天:电商行业的背景.淘淘商城的介绍.搭建项目工 ...

  8. (转)淘淘商城系列——使用maven构建工程

    http://blog.csdn.net/yerenyuan_pku/article/details/72669269 开发工具和环境 这里,我统一规范一下淘淘商城的开发工具和环境,如下: Eclip ...

  9. day68_淘淘商城项目_01

    原文:day68_淘淘商城项目_01 课程计划 第一天: 1.电商行业的背景介绍--电子商务 2.淘淘商城的系统架构 a) 功能介绍 b) 架构讲解 3.工程搭建--后台工程 a) 使用maven搭建 ...

  10. day68_淘淘商城项目_01_电商介绍 + 互联网术语 + SOA + 分布式 + 集群介绍 + 环境配置 + 框架搭建_匠心笔记

    课程计划 第一天: 1.电商行业的背景介绍--电子商务 2.淘淘商城的系统架构 a) 功能介绍 b) 架构讲解 3.工程搭建--后台工程 a) 使用maven搭建工程(工程大) b) 使用maven的 ...

随机推荐

  1. 测试linux是否能访问外网

    方法1 curl -l http://www.baidu.com 方法2 wget http://www.baidu.com

  2. 【转载】Hadoop Hive基础sql语法

    转自:http://www.cnblogs.com/HondaHsu/p/4346354.html Hive 是基于Hadoop 构建的一套数据仓库分析系统,它提供了丰富的SQL查询方式来分析存储在H ...

  3. laravel实现excel表的导入导出功能

    1.这是个我去公司之后曾经折磨我很久很久的功能查阅了很多资料但是功夫不负有心人在本人的不懈努力下还是实现了这个功能 (ps看不懂我下面说讲述的可以参考这个laravel学院的官方文档 https:// ...

  4. FP side-effects

    https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076be ...

  5. 使用ResponseBodyAdvice统一包装响应返回String的时候出现java.lang.ClassCastException: com.xxx.dto.common.ResponseResult cannot be cast to java.lang.String

    代码如下: @Override public ResponseResult<Object> beforeBodyWrite(Object returnValue, MethodParame ...

  6. 多数据源切换-Druid

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/qq_37279783/article/d ...

  7. angular项目实现mqtt的订阅与发布 ngx-mqtt

    angular项目实现mqtt的订阅与发布 如果要写一个exe可执行文件,可以使用angular编写,然后使用electron打包成一个exe文件. https://github.com/maxime ...

  8. [Luogu]小Z的AK计划

    Description Luogu2107 Solution 一开始打了一个60分的暴力DP,结果一分都没得--本地调了好久才发现是没开long long. 由于我的DP方程没有任何性质,就是一个01 ...

  9. Javaweb项目的命名规范

    项目名称:一般是英文 包名:公司域名的倒写,例如com.baidu 数据访问层:dao,persist,mapper 实体:entity,model,bean,javabean,pojo 业务逻辑:s ...

  10. Swagger-ui接口文档

    参考地址 https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview   ...