一、基本概述

1.1,什么是Httpclient

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

这只是简单介绍,详细了解:Httpclient home

特别注意:

The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better
performance and more flexibility.

简单点说,就是最好使用HttpComponents,它在Httpclient的基础上,提供了更好的服务!

1.2,Httpclient有什么用

简单总结来说,有以下四个功能:

(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

PS:建议查看文档:Httpclient features  ,简单又粗暴的说法就是,当你部署好了一个rest风格的接口服务,可以使用这个httpclient工具,进行接口访问以获取数据!

1.3,怎么用

使用 HttpClient 需要以下 6 个步骤:

1. 创建 HttpClient 的实例

2. 创建某种连接方法的实例,在这里是GetMethod。在 GetMethod 的构造函数中传入待连接的地址

3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

4. 读 response

5. 释放连接。无论执行方法是否成功,都必须释放连接

6. 对得到后的内容进行处理

简单示例代码:

<span style="font-family:KaiTi_GB2312;font-size:18px;">	public void doGetWithParam() throws Exception{
//创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个uri对象
URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
uriBuilder.addParameter("query", "花千骨");
HttpGet get = new HttpGet(uriBuilder.build());
//执行请求
CloseableHttpResponse response = httpClient.execute(get);
//取响应的结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
//关闭httpclient
response.close();
httpClient.close();
}</span>

二、代码封装

前提:maven导入依赖:

<span style="font-family:KaiTi_GB2312;font-size:18px;">package com.taotao.common.utils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; 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);
} public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
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;
}
}
</span>

IT界,最悲痛的事儿,莫过于,我错过了Struts1,我错过了Struts2,而我还将继续错过MVC。。。。很多东西在我刚知道的时候,发现人家已经过时了。这个行业发展的太快了,不进则退,奋斗吧,少年!

【Ts 5】Httpclient的应用和封装的更多相关文章

  1. Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)

    package com.ad.ssp.engine.common; import java.io.IOException; import java.util.ArrayList; import jav ...

  2. 接口自动化:HttpClient + TestNG + Java(四) - 封装和测试post方法请求

    在上一篇中,我们对第一个自动化接口测试用例做了初步优化和断言,这一篇我们处理POST请求. 4.1 发送POST方法请求 post方法和get方法是我们在做接口测试时,绝大部分场景下要应对的主要方法. ...

  3. 基于httpclient的一些常用方法封装

    package com.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import ja ...

  4. Httpclient Fluent API简单封装

    import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List ...

  5. WebApi系列~通过HttpClient来调用Web Api接口

    回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...

  6. 通过HttpClient来调用Web Api接口

    回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...

  7. 跨域问题解决方案(HttpClient安全跨域 & jsonp跨域)

    1 错误场景 今天要把项目部署到外网的时候,出现了这样的问题, 我把两个项目放到自己本机的tomcat下, 进行代码调试, 运行 都没有问题的, 一旦把我需要调用接口的项目B放到其他的服务器上, 就会 ...

  8. 多媒体文件格式(四):TS 格式

    一.TS 格式标准介绍 TS是一种音视频封装格式,全称为MPEG2-TS.其中TS即"Transport Stream"的缩写. 先简要介绍一下什么是MPEG2-TS: DVD的音 ...

  9. java中的http请求的封装(GET、POST、form表单形式)

    目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...

随机推荐

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

    文章大纲 一.课程介绍二.Redis基础实战三.Redis之高可用.集群.云平台搭建实战四.淘淘商城Jedis整合spring五.项目源码与资料下载六.参考文章   一.课程介绍 一共14天课程(1) ...

  2. 公司开发部门GIT与SVN 之争

    公司最开始决定是使用GIT作为版本控制 , 也都使用了4,5个月了 , 开发人员也都是20多岁年轻力壮的年轻人 , 每个组的组长也一直在做git使用的培训 , 即使是这样 , 还是遇到了非常大的阻碍 ...

  3. deepin15.2无线网无法使用

    原文链接:https://bbs.deepin.org/forum.php?mod=viewthread&tid=40276&highlight=%E6%97%A0%E7%BA%BF% ...

  4. js原生子级元素阻止父级元素冒泡事件

    <html> <head> <style type="text/css"> #hide{ width:75%;height:80px;backg ...

  5. uvm_monitor——借我一双慧眼

    monitor 用来捕获(监视)和检查总线的信号是否满足预期的要求.所有的user_monitor 继承自uvm_monitor,uvm_monitor继承自uvm_component,从源代码来看里 ...

  6. RStudio的Markdown

    Title This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages ...

  7. Yii2中多表关联查询(with、join、joinwith)

    表结构 现在有客户表.订单表.图书表.作者表, 客户表Customer   (id  customer_name) 订单表Order         (id  order_name   custome ...

  8. JAVA 配置

    JAVA 版本为jdk-7u25-windows-x64 Java 下载地址为: .CLASSPATH .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.j ...

  9. maven项目jsp无法识别jstl的解决办法

    EL表达式无效是因为maven项目的jsp不识别jstl,只要在web-APP 标签中引入命名空间 xmlns="http://xmlns.jcp.org/xml/ns/javaee&quo ...

  10. 剑指offer44 扑克牌顺序

    注意一个边界条件:必须是连续的,如果前后两个数是一样的也不满足条件 class Solution { public: bool IsContinuous( vector<int> numb ...