HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、 功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net 包中已经提 供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能 还不够丰富和灵活。
在创建Maven工程项目时,在pom.xml中添加如下坐标即可自动导入相关jar包
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
1、创建一个httpclient对象 2、创建Get请求对象,在请求中输入url 3、发送请求,并返回响应 4、处理响应, 获取响应的状态码 5、获取响应的内容 6、关闭连接
/**
* get请求不带参数
* @throws ClientProtocolException
* @throws IOException
*/
public static void doGet() throws ClientProtocolException, IOException {
//创建一个httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建Get请求对象,在请求中输入url
HttpGet Get = new HttpGet("http://www.baidu.com");
//发送请求,并返回响应
CloseableHttpResponse response = client.execute(Get);
//处理相应
//获取相应的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
//获取相应的内容
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity, "utf-8");
System.out.println(responseBody);
//关闭连接
client.close();
}
1、创建一个httpclient对象 2、封装一个uri对象,在该对象中可以指定参数 3、创建Get请求对象,在请求中输入url 3、发送请求,并返回响应 4、处理响应, 获取响应的状态码 5、获取响应的内容 6、关闭连接
/**
* get请求带参数
*
*/
public static void deGetParam() throws URISyntaxException, ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
//封装一个uri对象,在该对象中可以指定参数
URIBuilder uri = new URIBuilder("https://www.jianshu.com/search");
uri.addParameter("q","西游记");
//创建一个get请求对象
HttpGet get = new HttpGet(uri.build());
CloseableHttpResponse response = client.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);
client.close();
}
1、创建一个httpclient对象 2、创建 post 请求对象,在请求中输入url 3、发送请求,并返回响应 4、处理响应, 获取响应的状态码 5、获取响应的内容 6、关闭连接
/**
* post请求不带参
*/
public static void doPost() throws Exception{
//发送请求
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/post");
CloseableHttpResponse response = client.execute(post);
//处理响应
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("状态码"+statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println("网页内容"+string);
client.close();
}
1、创建一个httpclient对象 2、创建 post 请求对象,在请求中输入url 3、给定参数,将参数转换成字符串,并在post 请求中绑定参数 3、发送请求,并返回响应 4、处理响应, 获取响应的状态码 5、获取响应的内容 6、关闭连接
/**
* post请求带参数
*/
public static void doPostParam() throws Exception{
//发送请求
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/post/param");
//给定参数
ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("name", "时间静止"));
list.add(new BasicNameValuePair("pwd", "chy"));
//将参转换成字符串
StringEntity entity = new UrlEncodedFormEntity(list,"utf-8");
//向请求中韩绑定参数
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
//处理响应
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("状态码"+statusCode);
HttpEntity entit = response.getEntity();
String string = EntityUtils.toString(entit, "utf-8");
System.out.println("网页内容"+string);
client.close();
}
1、创建一个httpclient对象 2、创建 post 请求对象,在请求中输入url 3、创建一个json字符串,将其放入StringEntity中,指定类型,并在post 请求中绑定该字符串 4、发送请求,并返回响应 5、处理响应, 获取响应的状态码 6、获取响应的内容 7、关闭连接
/**
* post请求携带参数(json)
*/
public static void doPostParamJson() throws Exception{
//发送请求
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/post/param/json");
String json="{\"name\":\"时间静止\",\"pwd\":\"chy\"}";
StringEntity sentity=new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(sentity);
CloseableHttpResponse response = client.execute(post);
//处理响应
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("状态码"+statusCode);
HttpEntity entit = response.getEntity();
String string = EntityUtils.toString(entit, "utf-8");
System.out.println("网页内容"+string);
client.close();
}
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,"utf-8");
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;
}
}
使用工具类案例
使用的post请求携带参数
public static void TestHTTPClientUtil() {
String url="http://localhost:8080/test/post/param";
Map<String, String> param=new HashMap<String, String>();
param.put("name", "阿加");
param.put("pwd", "ues");
String result = HttpClientUtil.doPost(url, param);
System.out.println(result);
}