httpclient封装获取响应实体_HttpClient详细使用示例

进入正题

环境说明:JDK1.8、SpringBoot

准备环节

第一步:在pom.xml中引入HttpClient的依赖

第二步:引入fastjson依赖

注:本人引入此依赖的目的是,在后续示例中,会用到“将对象转化为json字符串的功能”,也可以引其他有此功能的依赖。

注:SpringBoot的基本依赖配置,这里就不再多说了。

详细使用示例

声明:此示例中,以;也是以JAVA接收的(在controller里面接收的)。

声明:下面的代码,本人亲测有效。

GET无参:

HttpClient发送示例:

@Test

public void doGetTestOne() {

// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)

CloseableHttpClient httpClient =

HttpClientBuilder.create().build();

// 创建Get请求

HttpGet httpGet = new

HttpGet("http://localhost:12345/doGetControllerOne");

// 响应模型

CloseableHttpResponse response = null;

try {

// 由客户端执行(发送)Get请求

response = httpClient.execute(httpGet);

// 从响应模型中获取响应实体

HttpEntity responseEntity = response.getEntity();

System.out.println("响应状态为:" + response.getStatusLine());

if (responseEntity != null) {

System.out.println("响应内容长度为:" +

responseEntity.getContentLength());

System.out.println("响应内容为:" +

EntityUtils.toString(responseEntity));

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

// 释放资源

if (httpClient != null) {

httpClient.close();

}

if (response != null) {

response.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

对应接收示例:

GET有参(方式一:直接拼接URL):

HttpClient发送示例:

@Test

public void doGetTestWayOne() {

// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)

CloseableHttpClient httpClient =

HttpClientBuilder.create().build();

// 参数

StringBuffer params = new StringBuffer();

try {

//

字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)

params.append("name=" + URLEncoder.encode("&",

"utf-8"));

params.append("&");

params.append("age=24");

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

}

// 创建Get请求

HttpGet httpGet = new

HttpGet("http://localhost:12345/doGetControllerTwo" + "?" +

params);

// 响应模型

CloseableHttpResponse response = null;

try {

// 配置信息

RequestConfig requestConfig = RequestConfig.custom()

// 设置连接超时时间(单位毫秒)

.setConnectTimeout(5000)

// 设置请求超时时间(单位毫秒)

.setConnectionRequestTimeout(5000)

// socket读写超时时间(单位毫秒)

.setSocketTimeout(5000)

// 设置是否允许重定向(默认为true)

.setRedirectsEnabled(true).build();

// 将上面的配置信息 运用到这个Get请求里

httpGet.setConfig(requestConfig);

// 由客户端执行(发送)Get请求

response = httpClient.execute(httpGet);

// 从响应模型中获取响应实体

HttpEntity responseEntity = response.getEntity();

System.out.println("响应状态为:" + response.getStatusLine());

if (responseEntity != null) {

System.out.println("响应内容长度为:" +

responseEntity.getContentLength());

System.out.println("响应内容为:" +

EntityUtils.toString(responseEntity));

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

// 释放资源

if (httpClient != null) {

httpClient.close();

}

if (response != null) {

response.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

对应接收示例:

GET有参(方式二:使用URI获得HttpGet):

HttpClient发送示例:

@Test

public void doGetTestWayTwo() {

// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)

CloseableHttpClient httpClient =

HttpClientBuilder.create().build();

// 参数

URI uri = null;

try {

// 将参数放入键值对类NameValuePair中,再放入集合中

List params = new

ArrayList<>();

params.add(new BasicNameValuePair("name",

"&"));

params.add(new BasicNameValuePair("age", "18"));

// 设置uri信息,并将参数集合放入uri;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient是一个非常常用的HTTP客户端库,可以用于发送HTTP请求并接收响应。在封装HttpClient时,我们可以考虑以下几点: 1. 连接池管理:HttpClient可以通过连接池来管理HTTP连接,从而提高性能。我们可以设置最大连接数、每个路由的最大连接数等参数,以便更好地利用连接池。 2. 超时设置:在发送HTTP请求时,我们需要设置超时时间,以避免请求过程中出现阻塞或超时等问题。可以设置连接超时时间、读取超时时间等参数。 3. 异常处理:在发送HTTP请求时,可能会出现各种异常情况,例如网络异常、连接超时等。我们需要对这些异常进行处理,以便及时发现问题并进行处理。 4. 请求头设置:在发送HTTP请求时,我们需要设置请求头,以便服务器能够正确地处理请求。可以设置User-Agent、Content-Type等参数。 5. SSL支持:如果需要发送HTTPS请求,则需要支持SSL协议。可以通过配置SSLContext来实现SSL支持。 下面是一个简单的HttpClient封装示例: ```java public class HttpClientUtil { private static final int MAX_TOTAL = 200; private static final int MAX_PER_ROUTE = 50; private static final int CONNECT_TIMEOUT = 5000; private static final int SOCKET_TIMEOUT = 10000; private static CloseableHttpClient httpClient; static { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_PER_ROUTE); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(requestConfig) .build(); } public static String doGet(String url, Map<String, String> headers) throws IOException { HttpGet httpGet = new HttpGet(url); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } return null; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值