修复GET较长字符串数据时数据流中断的bug

This commit is contained in:
hanxuanyu 2022-02-07 20:54:42 +08:00
parent ddf4b4bc07
commit e91812f942
4 changed files with 190 additions and 150 deletions

View File

@ -1,7 +1,7 @@
package com.hxuanyu.network.service; package com.hxuanyu.network.service;
import com.hxuanyu.common.message.Msg; import com.hxuanyu.common.message.Msg;
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse;
import java.util.Map; import java.util.Map;
@ -20,7 +20,7 @@ public interface HttpService {
* @param url 请求地址 * @param url 请求地址
* @return 统一结果报文 * @return 统一结果报文
*/ */
Msg<HttpEntity> doGetWithEntity(String url); Msg<HttpResponse> doGetWithResponse(String url);
@ -47,7 +47,7 @@ public interface HttpService {
* @param url 请求地址 * @param url 请求地址
* @param listener 异步请求结果监听 * @param listener 异步请求结果监听
*/ */
void doGetSyncWithEntity(String url, NetWorkListener<HttpEntity> listener); void doGetSyncWithResponse(String url, NetWorkListener<HttpResponse> listener);
/** /**
* 发送get请求带请求参数 * 发送get请求带请求参数
@ -66,7 +66,7 @@ public interface HttpService {
* @param params 请求参数集合 * @param params 请求参数集合
* @return 全局报文 * @return 全局报文
*/ */
Msg<HttpEntity> doGetWithEntity(String url, Map<String, String> params); Msg<HttpResponse> doGetWithResponse(String url, Map<String, String> params);
/** /**
* 异步Get请求 * 异步Get请求
@ -84,7 +84,7 @@ public interface HttpService {
* @param params 请求参数 * @param params 请求参数
* @param listener 异步请求结果监听 * @param listener 异步请求结果监听
*/ */
void doGetSyncWithEntity(String url, Map<String, String> params, NetWorkListener<HttpEntity> listener); void doGetSyncWithResponse(String url, Map<String, String> params, NetWorkListener<HttpResponse> listener);
/** /**
* 发送get请求带请求头和请求参数 * 发送get请求带请求头和请求参数
@ -104,7 +104,7 @@ public interface HttpService {
* @param params 请求参数集合 * @param params 请求参数集合
* @return 全局报文 * @return 全局报文
*/ */
Msg<HttpEntity> doGetWithEntity(String url, Map<String, String> headers, Map<String, String> params); Msg<HttpResponse> doGetWithResponse(String url, Map<String, String> headers, Map<String, String> params);
/** /**
* 异步Get请求 * 异步Get请求
@ -124,7 +124,7 @@ public interface HttpService {
* @param params 请求体 * @param params 请求体
* @param listener 异步结果监听器 * @param listener 异步结果监听器
*/ */
void doGetSyncWithEntity(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpEntity> listener); void doGetSyncWithResponse(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpResponse> listener);
/** /**
* 发送post请求不带请求头和请求参数 * 发送post请求不带请求头和请求参数
@ -140,7 +140,7 @@ public interface HttpService {
* @param url 请求地址 * @param url 请求地址
* @return 统一报文 * @return 统一报文
*/ */
Msg<HttpEntity> doPostWithEntity(String url); Msg<HttpResponse> doPostWithResponse(String url);
/** /**
@ -157,7 +157,7 @@ public interface HttpService {
* @param url 请求地址 * @param url 请求地址
* @param listener 请求参数 * @param listener 请求参数
*/ */
void doPostSyncWithEntity(String url, NetWorkListener<HttpEntity> listener); void doPostSyncWithResponse(String url, NetWorkListener<HttpResponse> listener);
/** /**
* 同步Post请求 * 同步Post请求
@ -176,7 +176,7 @@ public interface HttpService {
* @param params 请求参数 * @param params 请求参数
* @return 统一消息体 * @return 统一消息体
*/ */
Msg<HttpEntity> doPostWithEntity(String url, Map<String, String> params); Msg<HttpResponse> doPostWithResponse(String url, Map<String, String> params);
/** /**
* 异步Post请求 * 异步Post请求
@ -194,7 +194,7 @@ public interface HttpService {
* @param params 请求参数 * @param params 请求参数
* @param listener 异步请求结果监听 * @param listener 异步请求结果监听
*/ */
void doPostSyncWithEntity(String url, Map<String, String> params, NetWorkListener<HttpEntity> listener); void doPostSyncWithResponse(String url, Map<String, String> params, NetWorkListener<HttpResponse> listener);
/** /**
* 发送post请求带请求头和请求参数 * 发送post请求带请求头和请求参数
@ -214,7 +214,7 @@ public interface HttpService {
* @param params 请求参数集合 * @param params 请求参数集合
* @return 统一返回报文 * @return 统一返回报文
*/ */
Msg<HttpEntity> doPostWithEntity(String url, Map<String, String> headers, Map<String, String> params); Msg<HttpResponse> doPostWithResponse(String url, Map<String, String> headers, Map<String, String> params);
/** /**
@ -235,7 +235,7 @@ public interface HttpService {
* @param params 请求参数 * @param params 请求参数
* @param listener 异步请求结果监听 * @param listener 异步请求结果监听
*/ */
void doPostSyncWithEntity(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpEntity> listener); void doPostSyncWithResponse(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpResponse> listener);
/** /**
* 发送put请求不带请求参数 * 发送put请求不带请求参数
@ -252,7 +252,7 @@ public interface HttpService {
* @param url 请求地址 * @param url 请求地址
* @return 统一消息返回报文 * @return 统一消息返回报文
*/ */
Msg<HttpEntity> doPutWithEntity(String url); Msg<HttpResponse> doPutWithResponse(String url);
/** /**
* 发送put请求带请求参数 * 发送put请求带请求参数
@ -270,7 +270,7 @@ public interface HttpService {
* @param params 请求参数 * @param params 请求参数
* @return 统一消息报文 * @return 统一消息报文
*/ */
Msg<HttpEntity> doPutWithEntity(String url, Map<String, String> params); Msg<HttpResponse> doPutWithResponse(String url, Map<String, String> params);
/** /**
* 发送delete请求不带请求参数 * 发送delete请求不带请求参数
@ -286,7 +286,7 @@ public interface HttpService {
* @param url 请求地址 * @param url 请求地址
* @return 统一返回报文 * @return 统一返回报文
*/ */
Msg<HttpEntity> doDeleteWithEntity(String url); Msg<HttpResponse> doDeleteWithResponse(String url);
/** /**
* 发送delete请求带请求参数 * 发送delete请求带请求参数
@ -305,7 +305,7 @@ public interface HttpService {
* @param params 请求参数 * @param params 请求参数
* @return 统一返回报文 * @return 统一返回报文
*/ */
Msg<HttpEntity> doDeleteWithEntity(String url, Map<String, String> params); Msg<HttpResponse> doDeleteWithResponse(String url, Map<String, String> params);
interface NetWorkListener<T> { interface NetWorkListener<T> {
/** /**

View File

@ -2,13 +2,12 @@ package com.hxuanyu.network.service.impl;
import com.hxuanyu.common.message.Msg; import com.hxuanyu.common.message.Msg;
import com.hxuanyu.network.service.HttpService; import com.hxuanyu.network.service.HttpService;
import org.apache.http.HttpEntity; import org.apache.http.*;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
@ -21,6 +20,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*; import java.util.*;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
@ -56,9 +56,9 @@ public class HttpServiceImpl implements HttpService {
@Override @Override
public Msg<HttpEntity> doGetWithEntity(String url) { public Msg<HttpResponse> doGetWithResponse(String url) {
return doGetWithEntity(url, null, null); return doGetWithResponse(url, null, null);
} }
@Override @Override
@ -72,8 +72,8 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public void doGetSyncWithEntity(String url, NetWorkListener<HttpEntity> listener) { public void doGetSyncWithResponse(String url, NetWorkListener<HttpResponse> listener) {
doGetSyncWithEntity(url, null, listener); doGetSyncWithResponse(url, null, listener);
} }
@ -83,8 +83,8 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public Msg<HttpEntity> doGetWithEntity(String url, Map<String, String> params) { public Msg<HttpResponse> doGetWithResponse(String url, Map<String, String> params) {
return doGetWithEntity(url, null, params); return doGetWithResponse(url, null, params);
} }
@Override @Override
@ -93,54 +93,70 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public void doGetSyncWithEntity(String url, Map<String, String> params, NetWorkListener<HttpEntity> listener) { public void doGetSyncWithResponse(String url, Map<String, String> params, NetWorkListener<HttpResponse> listener) {
doGetSyncWithEntity(url, null, params, listener); doGetSyncWithResponse(url, null, params, listener);
} }
@Override @Override
public Msg<String> doGet(String url, Map<String, String> headers, Map<String, String> params) { public Msg<String> doGet(String url, Map<String, String> headers, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doGetWithEntity(url, headers, params);
return getStringMsg(httpEntityMsg);
}
@Override
public Msg<HttpEntity> doGetWithEntity(String url, Map<String, String> headers, Map<String, String> params) {
// 创建httpClient对象 // 创建httpClient对象
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建访问的地址 // 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url); HttpGet httpGet = buildHttpGet(url, params, headers);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/*
* setConnectTimeout设置连接超时时间单位毫秒
* setConnectionRequestTimeout设置从connect Manager(连接池)获取Connection
* 超时时间单位毫秒这个属性是新加的属性因为目前版本是可以共享连接池的
* setSocketTimeout请求获取数据的超时时间(即响应时间)单位毫秒 如果访问一个接口多少时间内无法返回数据就直接放弃此次调用
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 创建httpResponse对象 // 创建httpResponse对象
CloseableHttpResponse httpResponse = null; CloseableHttpResponse httpResponse = null;
// 执行请求并获得响应结果 // 执行请求并获得响应结果
Msg<HttpResponse> httpClientResult = getHttpClientResult(httpClient, httpGet);
if (httpClientResult.isSuccess()) {
String result = EntityUtils.toString(httpClientResult.getData().getEntity());
return Msg.success("请求成功[" + httpClientResult.getCode() + "]", result);
} else {
return Msg.failed("请求失败[" + httpClientResult.getCode() + "]");
}
} catch (Exception e) {
logger.error("请求过程出现异常: {}", e.getMessage());
return Msg.failed("请求过程中出现异常" + e.getMessage());
}
}
@Override
public Msg<HttpResponse> doGetWithResponse(String url, Map<String, String> headers, Map<String, String> params) {
// 创建httpClient对象
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = buildHttpGet(url, params, headers);
// 执行请求并获得响应结果
return getHttpClientResult(httpClient, httpGet); return getHttpClientResult(httpClient, httpGet);
} catch (Exception e) { } catch (Exception e) {
logger.error("请求过程出现异常: {}", e.getMessage()); logger.error("请求过程出现异常: {}", e.getMessage());
return Msg.failed("网络请求发生异常:" + e.getMessage()); return Msg.failed("请求过程中出现异常" + e.getMessage());
} }
} }
private HttpGet buildHttpGet(String url, Map<String, String> params, Map<String, String> headers) throws URISyntaxException {
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
return httpGet;
}
@Override @Override
public void doGetSync(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<String> listener) { public void doGetSync(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<String> listener) {
@ -161,10 +177,10 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public void doGetSyncWithEntity(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpEntity> listener) { public void doGetSyncWithResponse(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpResponse> listener) {
executorService.execute(() -> { executorService.execute(() -> {
try { try {
Msg<HttpEntity> msg = doGetWithEntity(url, headers, params); Msg<HttpResponse> msg = doGetWithResponse(url, headers, params);
logger.debug("异步请求结果:{}", msg); logger.debug("异步请求结果:{}", msg);
if (msg.getCode().equals(Msg.MSG_CODE_SUCCESS)) { if (msg.getCode().equals(Msg.MSG_CODE_SUCCESS)) {
listener.onSuccess(msg); listener.onSuccess(msg);
@ -184,8 +200,8 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public Msg<HttpEntity> doPostWithEntity(String url) { public Msg<HttpResponse> doPostWithResponse(String url) {
return doPostWithEntity(url, null, null); return doPostWithResponse(url, null, null);
} }
@Override @Override
@ -194,8 +210,8 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public void doPostSyncWithEntity(String url, NetWorkListener<HttpEntity> listener) { public void doPostSyncWithResponse(String url, NetWorkListener<HttpResponse> listener) {
doPostSyncWithEntity(url, null, listener); doPostSyncWithResponse(url, null, listener);
} }
@ -205,8 +221,8 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public Msg<HttpEntity> doPostWithEntity(String url, Map<String, String> params) { public Msg<HttpResponse> doPostWithResponse(String url, Map<String, String> params) {
return doPostWithEntity(url, null, params); return doPostWithResponse(url, null, params);
} }
@Override @Override
@ -215,40 +231,32 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public void doPostSyncWithEntity(String url, Map<String, String> params, NetWorkListener<HttpEntity> listener) { public void doPostSyncWithResponse(String url, Map<String, String> params, NetWorkListener<HttpResponse> listener) {
doPostSyncWithEntity(url, null, params, listener); doPostSyncWithResponse(url, null, params, listener);
} }
@Override @Override
public Msg<String> doPost(String url, Map<String, String> headers, Map<String, String> params) { public Msg<String> doPost(String url, Map<String, String> headers, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doPostWithEntity(url, headers, params); Msg<HttpResponse> httpResponseMsg = doPostWithResponse(url, headers, params);
return getStringMsg(httpEntityMsg); String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
} }
@Override @Override
public Msg<HttpEntity> doPostWithEntity(String url, Map<String, String> headers, Map<String, String> params) { public Msg<HttpResponse> doPostWithResponse(String url, Map<String, String> headers, Map<String, String> params) {
// 创建httpClient对象 // 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象 // 创建http对象
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
/*
* setConnectTimeout设置连接超时时间单位毫秒
* setConnectionRequestTimeout设置从connect Manager(连接池)获取Connection
* 超时时间单位毫秒这个属性是新加的属性因为目前版本是可以共享连接池的
* setSocketTimeout请求获取数据的超时时间(即响应时间)单位毫秒 如果访问一个接口多少时间内无法返回数据就直接放弃此次调用
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
// 设置请求头
// httpPost.setHeader("Cookie", "");
// httpPost.setHeader("Connection", "keep-alive");
// httpPost.setHeader("Accept", "application/json");
// httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
// httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
// httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
packageHeader(headers, httpPost); packageHeader(headers, httpPost);
// 封装请求参数 // 封装请求参数
try { try {
packageParam(params, httpPost); packageParam(params, httpPost);
@ -279,10 +287,10 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public void doPostSyncWithEntity(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpEntity> listener) { public void doPostSyncWithResponse(String url, Map<String, String> headers, Map<String, String> params, NetWorkListener<HttpResponse> listener) {
executorService.execute(() -> { executorService.execute(() -> {
try { try {
Msg<HttpEntity> msg = doPostWithEntity(url, headers, params); Msg<HttpResponse> msg = doPostWithResponse(url, headers, params);
if (msg.getCode().equals(Msg.MSG_CODE_SUCCESS)) { if (msg.getCode().equals(Msg.MSG_CODE_SUCCESS)) {
listener.onSuccess(msg); listener.onSuccess(msg);
} else if (msg.getCode().equals(Msg.MSG_CODE_FAILED)) { } else if (msg.getCode().equals(Msg.MSG_CODE_FAILED)) {
@ -302,18 +310,26 @@ public class HttpServiceImpl implements HttpService {
} }
@Override @Override
public Msg<HttpEntity> doPutWithEntity(String url) { public Msg<HttpResponse> doPutWithResponse(String url) {
return doPutWithEntity(url, null); return doPutWithResponse(url, null);
} }
@Override @Override
public Msg<String> doPut(String url, Map<String, String> params) { public Msg<String> doPut(String url, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doPutWithEntity(url, params); Msg<HttpResponse> httpResponseMsg = doPutWithResponse(url, params);
return getStringMsg(httpEntityMsg); String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
} }
@Override @Override
public Msg<HttpEntity> doPutWithEntity(String url, Map<String, String> params) { public Msg<HttpResponse> doPutWithResponse(String url, Map<String, String> params) {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url); HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
@ -331,32 +347,23 @@ public class HttpServiceImpl implements HttpService {
} }
} }
private String parseEntityToString(HttpEntity httpEntity) throws IOException {
return EntityUtils.toString(httpEntity, ENCODING);
}
private Msg<String> getStringMsg(Msg<HttpEntity> httpEntityMsg) { @Override
if (Msg.MSG_CODE_SUCCESS.equals(httpEntityMsg.getCode())) { public Msg<String> doDelete(String url) {
try { Msg<HttpResponse> httpResponseMsg = doDeleteWithResponse(url);
String result = parseEntityToString(httpEntityMsg.getData()); String stringResult;
return Msg.success(httpEntityMsg.getMsg(), result); try {
} catch (IOException e) { stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
e.printStackTrace(); return Msg.success("请求成功", stringResult);
return Msg.failed("转换字符串过程中发生异常:" + e.getMessage()); } catch (IOException e) {
} e.printStackTrace();
} else { return Msg.failed("转换字符串失败:" + e.getMessage());
return Msg.failed(httpEntityMsg.getMsg());
} }
} }
@Override @Override
public Msg<String> doDelete(String url) { public Msg<HttpResponse> doDeleteWithResponse(String url) {
Msg<HttpEntity> httpEntityMsg = doDeleteWithEntity(url); // 创建httpClient对象
return getStringMsg(httpEntityMsg);
}
@Override
public Msg<HttpEntity> doDeleteWithEntity(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url); HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
@ -371,18 +378,25 @@ public class HttpServiceImpl implements HttpService {
@Override @Override
public Msg<String> doDelete(String url, Map<String, String> params) { public Msg<String> doDelete(String url, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doDeleteWithEntity(url, params); Msg<HttpResponse> httpResponseMsg = doDeleteWithResponse(url, params);
return getStringMsg(httpEntityMsg); String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
} }
@Override @Override
public Msg<HttpEntity> doDeleteWithEntity(String url, Map<String, String> params){ public Msg<HttpResponse> doDeleteWithResponse(String url, Map<String, String> params) {
if (params == null) { if (params == null) {
params = new HashMap<>(0); params = new HashMap<>(0);
} }
params.put("_method", "delete"); params.put("_method", "delete");
return doPostWithEntity(url, params); return doPostWithResponse(url, params);
} }
@ -412,27 +426,15 @@ public class HttpServiceImpl implements HttpService {
} }
} }
private Msg<HttpEntity> getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod) { private Msg<HttpResponse> getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws IOException {
// 执行请求 // 执行请求
CloseableHttpResponse httpResponse; CloseableHttpResponse httpResponse;
try { logger.info("执行请求:{},请求方式:{}", httpMethod.getURI().toString(), httpMethod.getMethod());
logger.info("执行请求:{},请求方式:{}", httpMethod.getURI().toString(), httpMethod.getMethod()); httpResponse = httpClient.execute(httpMethod);
httpResponse = httpClient.execute(httpMethod); // 获取返回结果
// 获取返回结果 if (httpResponse != null && httpResponse.getStatusLine() != null) {
if (httpResponse != null && httpResponse.getStatusLine() != null) { return Msg.success("请求成功", httpResponse);
HttpEntity content;
if (httpResponse.getEntity() != null) {
content = httpResponse.getEntity();
return Msg.success(httpResponse.getStatusLine().getStatusCode() + "请求成功", content);
}
}
} catch (IOException e) {
e.printStackTrace();
logger.error("请求过程中出现异常: {}", e.getMessage());
return Msg.failed("请求过程出现异常" + e.getMessage());
} }
return Msg.failed(HttpStatus.SC_INTERNAL_SERVER_ERROR + "请求失败"); return Msg.failed(HttpStatus.SC_INTERNAL_SERVER_ERROR + "请求失败");
} }

View File

@ -0,0 +1,51 @@
package com.hxuanyu.starter.test;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class OtherTest {
private static final String STATION_NAME_URL = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9226";
@Test
public void testHttpClient() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet(STATION_NAME_URL);
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
try (CloseableHttpResponse response = httpclient.execute(httpget)) {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -5,17 +5,11 @@ import com.hxuanyu.network.service.HttpService;
import com.hxuanyu.test.MainApplication; import com.hxuanyu.test.MainApplication;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.Timeout;
import org.junit.runner.RunWith;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Thread.sleep;
@SpringBootTest(classes = MainApplication.class) @SpringBootTest(classes = MainApplication.class)
public class NetworkTest { public class NetworkTest {
@ -24,18 +18,11 @@ public class NetworkTest {
HttpService httpService; HttpService httpService;
private final Logger logger = LoggerFactory.getLogger(NetworkTest.class); private final Logger logger = LoggerFactory.getLogger(NetworkTest.class);
private static final String STATION_NAME_URL = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9226";
@Test @Test
@Timeout(3000) @Timeout(3000)
public void testGet() throws InterruptedException { public void testGet(){
Map<String, String> header = new HashMap<>(1); Msg<String> msg = httpService.doGet("https://baidu.com");
// header.put("Accept", "*/*");
header.put("Connection", "keep-alive");
// header.put("User-Agent", "PostmanRuntime/7.29.0");
// header.put("Accept-Encoding", "gzip, deflate, br");
Msg<String> msg = httpService.doGet(STATION_NAME_URL, header, null);
logger.info("GET测试{}", msg); logger.info("GET测试{}", msg);
assert msg.isSuccess(); assert msg.isSuccess();
} }