(一)简介

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

随机推荐

  1. 360 网络攻防 hackgame 解题报告(通关)

    地址:http://challenge.onebox.so.com/ 1.referrer or host 2.js decode 3.urldecode, ASCII 4.JFIF * 2 5.go ...

  2. linux下使用Stunnel配置与使用方式一例

    第一部分:stunnel的安装与配置 注:在ubuntu下,stunnel的安装很简单快捷. 在synaptic(安立得工具系统下可以直接选举安装) 在服务器环境下,直接使用apt-get insta ...

  3. 【实用】如何在windows下快速截图?

    如何在windows下快速截图? 快速截图是很多人的需求.截图的工具和方案也很多,但是,这里给出一个通用的,被大众认为最高效的一个解决方案. 我们都知道键盘上有一个"prt sc" ...

  4. 【Mac安装,ATX基于uiautomator2】之安装步骤

    Mac系统下安装uiaotumator2: 参考网址:<uiautomator2>以及参考github官方文档 注意:下面有坑,如果你没有下面的问题请直接跳转到 1.安装uiaotumat ...

  5. Java基础11 对象引用(转载)

    对象引用 我们沿用之前定义的Human类,并有一个Test类:  public class Test{    public static void main(String[] args){       ...

  6. 【转】Monkey测试2——Monkey测试策略

    Monkey的测试策略 一. 分类 Monkey测试针对不同的对象和不同的目的采用不同的测试方案,首先测试的对象.目的及类型如下: 测试的类型分为:应用程序的稳定性测试和压力测试 测试对象分为:单一a ...

  7. Android ADB工具-操作手机和获取手设备信息(四)

    Android ADB工具-操作手机和获取手设备信息(四) 标签(空格分隔): Android ADB 6. 其它命令 命令 功能 adb shell input text <content&g ...

  8. Unity3D学习笔记——UIScrollBar和UIScrollView使用

    UIScrollBar和UIScrollView结合使用效果图如下: 一:使用步骤  1.创建一个UIScrollView   2.然后创建一个UIScrollBar 3.打开UIScrollView ...

  9. centos7 笔记本盒盖不睡眠

    cd /etc/systemd vi logind.conf 动作包括:HandlePowerKey:按下电源键后的动作HandleSleepKey:按下挂起键后的动作HandleHibernateK ...

  10. LUA速成教程

    說明: 1.該教程適合對編程有一定了解的人員. 2.該教程在WINDOWS下實驗. 切入正題, 1.首先下載Notepad++,工欲善其事,必先利其器,然後安裝NotePad++的插件NppExec. ...