【Ts 5】Httpclient的应用和封装
一、基本概述
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的应用和封装的更多相关文章
- Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)
package com.ad.ssp.engine.common; import java.io.IOException; import java.util.ArrayList; import jav ...
- 接口自动化:HttpClient + TestNG + Java(四) - 封装和测试post方法请求
在上一篇中,我们对第一个自动化接口测试用例做了初步优化和断言,这一篇我们处理POST请求. 4.1 发送POST方法请求 post方法和get方法是我们在做接口测试时,绝大部分场景下要应对的主要方法. ...
- 基于httpclient的一些常用方法封装
package com.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import ja ...
- Httpclient Fluent API简单封装
import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List ...
- WebApi系列~通过HttpClient来调用Web Api接口
回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...
- 通过HttpClient来调用Web Api接口
回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...
- 跨域问题解决方案(HttpClient安全跨域 & jsonp跨域)
1 错误场景 今天要把项目部署到外网的时候,出现了这样的问题, 我把两个项目放到自己本机的tomcat下, 进行代码调试, 运行 都没有问题的, 一旦把我需要调用接口的项目B放到其他的服务器上, 就会 ...
- 多媒体文件格式(四):TS 格式
一.TS 格式标准介绍 TS是一种音视频封装格式,全称为MPEG2-TS.其中TS即"Transport Stream"的缩写. 先简要介绍一下什么是MPEG2-TS: DVD的音 ...
- java中的http请求的封装(GET、POST、form表单形式)
目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...
随机推荐
- VMware网络适配器设置
VMware网络连接主要有三种方式,分别是桥接,NAT和Host-only. 桥接:直接使用的是真实机的物理网卡(有线网卡,无线网卡),会占用局域网中的一个IP,因此在设置虚拟机IP时要避免与同网段的 ...
- Tunneling cannot be enabled without the local_ip bound to an interface on the host. Please configure local_ip 192.168.30.71 on the host interface to be used for tunneling and restart the agen
按照官方文档配置linux bridge 会出现一下问题 Tunneling cannot be enabled without the local_ip bound to an interface ...
- openstack No valid host was found. There are not enough hosts available.
root@dell-PowerEdge-T30:~# gedit /var/log/nova/nova-conductor.logroot@dell-PowerEdge-T30:~# gedit /v ...
- 博客-从github ghpage 转回通知
博客迁回 这是我的github博客:http://www.flyfishonline.com/ 原因一 某QQ朋友:"......看了你的简历,根据你(github)博客看,似乎简历包装的过 ...
- Eclipse 和 MyEclipse 工程描述符
有时候在一个Java工程里我们需要加入第三方jar包,这时你加入的最好相对路径, 而不是绝对路径.否则你的工程拿到别处就不行运行了.意思就是说你最好把相关的jar放到工程目录下. 对于Web工程来说相 ...
- 关于img
为img添加属性max-width min-height之类的属性可以对图片溢出部分实行自动裁剪功能 非常方便!!!!!!!!!(仅适用于那些原始图片大于max-width,max-height的图片 ...
- Asp.Net Core 进阶(二) —— 集成Log4net
Asp.Net Core 支持适用于各种内置日志记录API,同时也支持其他第三方日志记录.在我们新建项目后,在Program 文件入口调用了CreateDefaultBuilder,该操作默认将添加以 ...
- 身份证号正则校验(js校验+JAVA校验)
js校验身份证号[15位和18位] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 3 ...
- java在线聊天项目0.7版 连接多个客户端问题,开启多个客户端后服务器端只接收到一个 对各种异常的补充处理
问题的原因是 while(connected) { String str=dis.readUTF(); System.out.println(str); } 不断循环执行,一直在死循环获取socket ...
- DP入门练习
T1 题目:codevs4815江哥的dp题a codevs4815 一个简单的DP,注意开long long(不然会全WA),以及初始条件(这题有负数,所以要把f设成极小值.还要保证转移正确). # ...