$Java HttpClient库的使用
(一)简介
HttpClient是Apache的一个开源库,相比于JDK自带的URLConnection等,使用起来更灵活方便。
使用方法可以大致分为如下八步曲:
1、创建一个HttpClient对象;
2、创建一个Http请求对象并设置请求的URL,比如GET请求就创建一个HttpGet对象,POST请求就创建一个HttpPost对象;
3、如果需要可以设置请求对象的请求头参数,也可以往请求对象中添加请求参数;
4、调用HttpClient对象的execute方法执行请求;
5、获取请求响应对象和响应Entity;
6、从响应对象中获取响应状态,从响应Entity中获取响应内容;
7、关闭响应对象;
8、关闭HttpClient.
(二)在本地创建一个Servlet程序
在本地创建一个Servlet程序并跑在Tomcat服务器中,主要用于下一步测试HttpClient发送请求。
注:Servlet的创建方法详见:微信公众号开发【技术基础】(一):Eclipse+Tomcat搭建本地服务器并跑通HelloWorld程序
1、Servlet类:
import java.io.PrintWriter; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 4601029764222607869L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
// 1. 设置编码格式
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8"); // 2. 往返回体中写返回数据
PrintWriter writer = null;
try {
writer = resp.getWriter();
writer.print("Hello world! 你好,世界!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
writer.close();
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// 1. 获取请求的参数
String userName = req.getParameter("username");
String password = req.getParameter("password"); // 2. 往返回体写返回数据
PrintWriter writer = null;
try {
writer = resp.getWriter();
writer.print("your username is:" + userName + "\nyour password is:" + password);
} catch (Exception e) {
e.printStackTrace();
} finally {
writer.close();
}
} }
2、web.xml(新加内容):
<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>com.servlet.HelloWorld</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
(三)测试HttpClient发送GET和POST请求
1、HttpClient测试类:
package com.test.method; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* 测试HttpClient发送各种请求的方法
*
* @author Administrator
*
*/
public class HttpClientTest {
// 发送请求的url
public static final String REQUEST_URL = "http://localhost:8080/TomcatTest/hello"; /**
* 测试发送GET请求
*/
public void get() {
// 1. 创建一个默认的client实例
CloseableHttpClient client = HttpClients.createDefault(); try {
// 2. 创建一个httpget对象
HttpGet httpGet = new HttpGet(REQUEST_URL);
System.out.println("executing GET request " + httpGet.getURI()); // 3. 执行GET请求并获取响应对象
CloseableHttpResponse resp = client.execute(httpGet); try {
// 4. 获取响应体
HttpEntity entity = resp.getEntity();
System.out.println("------"); // 5. 打印响应状态
System.out.println(resp.getStatusLine()); // 6. 打印响应长度和响应内容
if (null != entity) {
System.out.println("Response content length = " + entity.getContentLength());
System.out.println("Response content is:\n" + EntityUtils.toString(entity));
} System.out.println("------");
} finally {
// 7. 无论请求成功与否都要关闭resp
resp.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 8. 最终要关闭连接,释放资源
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} /**
* 测试发送POST请求
*/
public void post() {
// 1. 获取默认的client实例
CloseableHttpClient client = HttpClients.createDefault();
// 2. 创建httppost实例
HttpPost httpPost = new HttpPost(REQUEST_URL);
// 3. 创建参数队列(键值对列表)
List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
paramPairs.add(new BasicNameValuePair("username", "admin"));
paramPairs.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity entity; try {
// 4. 将参数设置到entity对象中
entity = new UrlEncodedFormEntity(paramPairs, "UTF-8"); // 5. 将entity对象设置到httppost对象中
httpPost.setEntity(entity); System.out.println("executing POST request " + httpPost.getURI()); // 6. 发送请求并回去响应
CloseableHttpResponse resp = client.execute(httpPost); try {
// 7. 获取响应entity
HttpEntity respEntity = resp.getEntity(); // 8. 打印出响应内容
if (null != respEntity) {
System.out.println("------");
System.out.println(resp.getStatusLine());
System.out.println("Response content is : \n" + EntityUtils.toString(respEntity, "UTF-8")); System.out.println("------");
}
} finally {
// 9. 关闭响应对象
resp.close();
} } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 10. 关闭连接,释放资源
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
HttpClientTest test = new HttpClientTest();
// 测试GET请求
test.get();
// 测试POST请求
test.post();
}
}
2、输出结果:
executing GET request http://localhost:8080/TomcatTest/hello
------
HTTP/1.1 200 OK
Response content length = 34
Response content is:
Hello world! 你好,世界!!
------
executing POST request http://localhost:8080/TomcatTest/hello
------
HTTP/1.1 200 OK
Response content is :
your username is:admin
your password is:123456
------
(四)jar包下载
所需jar包打包下载地址:https://pan.baidu.com/s/1mhJ9iT6
随机推荐
- 配置AutoMapper映射规则《转》
配置AutoMapper映射规则 AutoMapper是基于约定的,因此在实用映射之前,我们需要先进行映射规则的配置. public class Source { public int SomeVal ...
- JavaScript-4.5 事件大全,事件监听---ShinePans
绑定事件 <input type="bubtton" onclick="javascript:alert('I am clicked');"> 处理 ...
- 【Mac + ATX基于uiautomator2】使用weditor时,报错:requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer'))
产生以下原因找到了:是因为启动了appium,两者冲突,不能同时使用. 之前讲过怎么安装u2([Mac安装,ATX基于uiautomator2]之安装步骤)以及使用weditor, 但是经过一段时间, ...
- 【OC学习-13】什么是组合,它和继承是什么关系?
继承有两缺点:(1)当层级越来越多时,假如每一个层级都有实例变量,那么最下层的子类继承的实例变量会超级多,沉重.(2)当消息传递自子类往上时.层级越多,效率越低下. 所以就有了组合.说实话区分继承和组 ...
- Unity3D学习笔记——NGUI之Localization system
Localization system(国际化系统) 实现的就是用户选择不同的语言,切换我们游戏文字的显示. 一:创建一个CVS文件.可以用Google Docs, Excel等软件工具. 我这里用的 ...
- poj 2516(拆点+最小权匹配)
题目链接:http://poj.org/problem?id=2516 思路:考虑某种货物,由于某个订货商可能接受来自不同地区的货物,而某一地区的货物也可能送给不同的订货商,显然不能直接进行匹配,必须 ...
- ios --跳转到支付宝
//跳转到支付宝 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request nav ...
- [Python2.x] 利用commands模块执行Linux shell命令
用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands模块的3个主要 ...
- ajax的适用场景
1.适用:基本所有的网站都有涉及到. 2.典型使用场景: 动态加载数据,按照需要取数据 改善用户体验 电子商务应用 访问第三方服务 数据局部刷新
- spring mvc3.1 @ResponseBody注解生成大量Accept-Charset
Spring3 MVC使用@ResponseBody后会产生非常大的响应头(Accept-Charset会达到4K+).原因在于默认情况下StringHttpMessageConverter.writ ...