(一)简介

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. OpenAPI初体验

    问题的一开始源于客户和服务部门抱怨我的REST API文档写得不好,然后又了解到 django rest framework 利用 coreapi 能自动生成文档,再就是看到 swagger.io 上 ...

  2. Java序列化的几种方式

    本文着重解说一下Java序列化的相关内容. 假设对Java序列化感兴趣的同学能够研究一下. 一.Java序列化的作用    有的时候我们想要把一个Java对象变成字节流的形式传出去,有的时候我们想要从 ...

  3. flask/sqlalchemy - OperationalError: (sqlite3.OperationalError) no such table

    狗书第五章 记得要先创建表 执行 db.create_all()语句来创建表 https://segmentfault.com/q/1010000005794140

  4. 多媒体开发之音频编码---ffmpeg 编码aac

    http://blog.csdn.net/ctroll/article/details/8169396

  5. 利用微信小程序实现web监控界面

    1.实现思路 利用小程序去调用公司zabbix的接口获取网站监控数据并展示出来. 2.准备阶段 1.小程序公众号 2.企业号 3.zabbix接口 3.实现过程

  6. merge实现拉链表

    建表如下( 历史拉链表): 新表(每日更新的): 实现语句: MERGE INTO test_target t1 USING ( SELECT nvl(c.id, b.id) AS id ,CASE ...

  7. ssl 生成证书

    使用OpenSSL生成证书 1.生成RSA密钥的方法 openssl genrsa -des3 -out privkey.pem 2048 这个命令会生成一个2048位的密钥,同时有一个des3方法加 ...

  8. python在linux中输出带颜色的文字的方法

    在开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中.而一般的应用服务器,第三方库,甚至服务器的一些通告也会在终端中显示,这样就搅乱了我们想要的信 ...

  9. Android 版本更新升级

    推荐一款很好的版本升级开源框架: https://github.com/WVector/AppUpdate 个人地址:总结https://gitee.com/anan9303/AppVersionUp ...

  10. 构造方法、this和super

    1.构造方法概述 创建对象的时候会调用构造方法.创建对象时需要给对象的属性初始化,这时需要有参的构造方法. 构造方法的格式: 修饰符 构造方法名(参数列表) { } 构造方法的体现: 构造方法没有返回 ...