HTTPClient使用

HttpClient
HttpClient 简介

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能 还不够丰富和灵活。

HttpClient 应用

pom.xml


4.0.0

<groupId>comm.bjsxt</groupId>
<artifactId>httpClientDemo</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.5</version>
    </dependency>
</dependencies>

发送 GET 请求不带参数
doGetParam()

/**
* 不带参
* @throws IOException
*/
public static void doGet() throws IOException {
//创建一个httpClient对象
CloseableHttpClient client= HttpClients.createDefault();
//创建Get请求对象
HttpGet get=new HttpGet("http://www.jd.com");
//发送请求并返回响应
CloseableHttpResponse execute = client.execute(get);
//处理响应
//获取响应的状态码
int code = execute.getStatusLine().getStatusCode();
System.out.println(code);
//获取响应的内容
HttpEntity entity=execute.getEntity();
String content= EntityUtils.toString(entity,"utf-8");
System.out.println(content);
//关闭连接
client.close();

}

发送 GET 请求带参数
doPost()

public static void doGetParam() throws IOException, URISyntaxException {
//创建一个httpClient对象
CloseableHttpClient client= HttpClients.createDefault();
//创建Get请求对象
URIBuilder bui=new URIBuilder("https://search.bilibili.com/all");
bui.addParameter("keyword","Python");
//发送请求并返回响应
HttpGet get=new HttpGet(bui.build());
CloseableHttpResponse execute = client.execute(get);
//处理响应
//获取响应的状态码
int code = execute.getStatusLine().getStatusCode();
System.out.println(code);
//获取响应的内容
HttpEntity entity=execute.getEntity();
String content= EntityUtils.toString(entity,"utf-8");
System.out.println(content);
//关闭连接
client.close();

}

发送 POST 请求不带参数

doPostParam()

public static void doPost() throws IOException {
//创建一个httpClient对象
CloseableHttpClient client= HttpClients.createDefault();
//创建Get请求对象
HttpPost post=new HttpPost("http://localhost:8080/test/post");
//发送请求并返回响应
CloseableHttpResponse execute = client.execute(post);
//处理响应
//获取响应的状态码
int code = execute.getStatusLine().getStatusCode();
System.out.println(code);
//获取响应的内容
HttpEntity entity=execute.getEntity();
String content= EntityUtils.toString(entity,"utf-8");
System.out.println(content);
//关闭连接
client.close();

}

发送 POST 请求带参数

doPostParam()

public static void doPostParam() throws IOException, URISyntaxException {
//创建一个httpClient对象
CloseableHttpClient client= HttpClients.createDefault();
//创建Post请求对象
HttpPost post=new HttpPost("http://localhost:8080/test/post/param");
//给定参数
List list=new ArrayList<>();
list.add(new BasicNameValuePair("name","张三丰"));
list.add(new BasicNameValuePair("pwd","zhangsanfeng"));
//将带参字符串转换
StringEntity en = new UrlEncodedFormEntity(list, "utf-8");
post.setEntity(en);

    //处理响应
    CloseableHttpResponse execute = client.execute(post);
    //获取响应的状态码
    int code = execute.getStatusLine().getStatusCode();
    System.out.println(code);
    //获取响应的内容
    HttpEntity entity=execute.getEntity();
    String content= EntityUtils.toString(entity,"utf-8");
    System.out.println(content);
    //关闭连接
    client.close();

}

在 POST 请求的参数中传递 JSON 格式数据

doPosJson()

public static void doPosJson() throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/post/param/json");
String json ="{"name":"张三丰","pwd":"zhangsanfeng"}";
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
//向请求中绑定参数
post.setEntity(entity);

    //处理响应
    CloseableHttpResponse res = client.execute(post);
    //获取响应的状态码
    int code = res.getStatusLine().getStatusCode();
    System.out.println(code);
    //获取响应的内容
    HttpEntity en = res.getEntity();
    String content = EntityUtils.toString(en,"utf-8");
    System.out.println(content);
    //关闭连接
    client.close();

}

HttpClient 自定义工具类的使用

package cn.ego.util;

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;
}

}

测试工具类

public static void httpClientUtilTest(){
String url = "http://localhost:8080/test/post/param";
Map<String, String> param = new HashMap<>();
param.put("name", "李四");
param.put("pwd", "lisi");
String result = HttpClientUtil.doPost(url, param);
System.out.println(result);
}

posted @ 2020-10-29 11:03  羊羊羊羊好多羊  阅读(72)  评论(0)    收藏  举报