5 Commits

15 changed files with 310 additions and 175 deletions

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>hxuanyu-spring-boot-starter-parent</artifactId>
<groupId>com.hxuanyu</groupId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -0,0 +1,16 @@
package com.hxuanyu.common.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* common 自动配置类
*
* @author hanxuanyu
* @version 1.0
*/
@Configuration
@ComponentScan("com.hxuanyu.common")
public class CommonConfiguration {
}

View File

@@ -0,0 +1,92 @@
package com.hxuanyu.common.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
/**
* SpringContext工具类用于获取全局ApplicationContext以及从中获取bean
*
* @author hanxuanyu
* @version 1.0
*/
@Component
@Lazy(false)
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
/**
* 主动向Spring容器中注册bean
*
* @param name BeanName
* @param clazz 注册的bean的类性
* @param args 构造方法的必要参数顺序和类型要求和clazz中定义的一致
* @param <T> 泛型
* @return 返回注册到容器中的bean对象
*/
public static <T> T registerBean(String name, Class<T> clazz, Object... args) {
return registerBean((ConfigurableApplicationContext) applicationContext, name, clazz, args);
}
/**
* 主动向Spring容器中注册bean
*
* @param applicationContext Spring容器
* @param name BeanName
* @param clazz 注册的bean的类性
* @param args 构造方法的必要参数顺序和类型要求和clazz中定义的一致
* @param <T> 泛型
* @return 返回注册到容器中的bean对象
*/
public static <T> T registerBean(ConfigurableApplicationContext applicationContext, String name, Class<T> clazz,
Object... args) {
if (applicationContext.containsBean(name)) {
Object bean = applicationContext.getBean(name);
if (bean.getClass().isAssignableFrom(clazz)) {
return (T) bean;
} else {
throw new RuntimeException("BeanName 重复 " + name);
}
}
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
for (Object arg : args) {
beanDefinitionBuilder.addConstructorArgValue(arg);
}
BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory();
beanFactory.registerBeanDefinition(name, beanDefinition);
return applicationContext.getBean(name, clazz);
}
}

View File

@@ -1,4 +1,4 @@
package com.hxuanyu.monitor.utils;
package com.hxuanyu.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@@ -12,6 +12,8 @@ import java.util.*;
* @version 1.0
*/
public class BeanUtils {
public static Field findField(Class<?> clazz, String name) {
try {
return clazz.getField(name);

View File

@@ -0,0 +1 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.hxuanyu.common.config.CommonConfiguration

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>hxuanyu-spring-boot-starter-parent</artifactId>
<groupId>com.hxuanyu</groupId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -1,6 +1,6 @@
package com.hxuanyu.monitor.config;
import com.hxuanyu.monitor.utils.BeanUtils;
import com.hxuanyu.common.util.BeanUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.SchedulingException;
import org.springframework.scheduling.TaskScheduler;

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>hxuanyu-spring-boot-starter-parent</artifactId>
<groupId>com.hxuanyu</groupId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

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

View File

@@ -2,13 +2,12 @@ package com.hxuanyu.network.service.impl;
import com.hxuanyu.common.message.Msg;
import com.hxuanyu.network.service.HttpService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
@@ -21,6 +20,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutorService;
@@ -56,9 +56,9 @@ public class HttpServiceImpl implements HttpService {
@Override
public Msg<HttpEntity> doGetWithEntity(String url) {
public Msg<HttpResponse> doGetWithResponse(String url) {
return doGetWithEntity(url, null, null);
return doGetWithResponse(url, null, null);
}
@Override
@@ -72,8 +72,8 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public void doGetSyncWithEntity(String url, NetWorkListener<HttpEntity> listener) {
doGetSyncWithEntity(url, null, listener);
public void doGetSyncWithResponse(String url, NetWorkListener<HttpResponse> listener) {
doGetSyncWithResponse(url, null, listener);
}
@@ -83,8 +83,8 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public Msg<HttpEntity> doGetWithEntity(String url, Map<String, String> params) {
return doGetWithEntity(url, null, params);
public Msg<HttpResponse> doGetWithResponse(String url, Map<String, String> params) {
return doGetWithResponse(url, null, params);
}
@Override
@@ -93,22 +93,48 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public void doGetSyncWithEntity(String url, Map<String, String> params, NetWorkListener<HttpEntity> listener) {
doGetSyncWithEntity(url, null, params, listener);
public void doGetSyncWithResponse(String url, Map<String, String> params, NetWorkListener<HttpResponse> listener) {
doGetSyncWithResponse(url, null, params, listener);
}
@Override
public Msg<String> doGet(String url, Map<String, String> headers, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doGetWithEntity(url, headers, params);
return getStringMsg(httpEntityMsg);
// 创建httpClient对象
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建访问的地址
HttpGet httpGet = buildHttpGet(url, params, headers);
// 创建httpResponse对象
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<HttpEntity> doGetWithEntity(String url, Map<String, String> headers, Map<String, String> params) {
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);
} catch (Exception e) {
logger.error("请求过程出现异常: {}", 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) {
@@ -117,35 +143,18 @@ public class HttpServiceImpl implements HttpService {
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();
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpClient, httpGet);
} finally {
// 释放资源
release(httpClient);
}
} catch (Exception e) {
logger.error("请求过程出现异常: {}", e.getMessage());
return Msg.failed("网络请求发生异常:" + e.getMessage());
}
return httpGet;
}
@@ -168,10 +177,10 @@ public class HttpServiceImpl implements HttpService {
}
@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(() -> {
try {
Msg<HttpEntity> msg = doGetWithEntity(url, headers, params);
Msg<HttpResponse> msg = doGetWithResponse(url, headers, params);
logger.debug("异步请求结果:{}", msg);
if (msg.getCode().equals(Msg.MSG_CODE_SUCCESS)) {
listener.onSuccess(msg);
@@ -191,8 +200,8 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public Msg<HttpEntity> doPostWithEntity(String url) {
return doPostWithEntity(url, null, null);
public Msg<HttpResponse> doPostWithResponse(String url) {
return doPostWithResponse(url, null, null);
}
@Override
@@ -201,8 +210,8 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public void doPostSyncWithEntity(String url, NetWorkListener<HttpEntity> listener) {
doPostSyncWithEntity(url, null, listener);
public void doPostSyncWithResponse(String url, NetWorkListener<HttpResponse> listener) {
doPostSyncWithResponse(url, null, listener);
}
@@ -212,8 +221,8 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public Msg<HttpEntity> doPostWithEntity(String url, Map<String, String> params) {
return doPostWithEntity(url, null, params);
public Msg<HttpResponse> doPostWithResponse(String url, Map<String, String> params) {
return doPostWithResponse(url, null, params);
}
@Override
@@ -222,40 +231,32 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public void doPostSyncWithEntity(String url, Map<String, String> params, NetWorkListener<HttpEntity> listener) {
doPostSyncWithEntity(url, null, params, listener);
public void doPostSyncWithResponse(String url, Map<String, String> params, NetWorkListener<HttpResponse> listener) {
doPostSyncWithResponse(url, null, params, listener);
}
@Override
public Msg<String> doPost(String url, Map<String, String> headers, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doPostWithEntity(url, headers, params);
return getStringMsg(httpEntityMsg);
Msg<HttpResponse> httpResponseMsg = doPostWithResponse(url, headers, params);
String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
}
@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对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/*
* setConnectTimeout设置连接超时时间单位毫秒。
* setConnectionRequestTimeout设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
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);
// 封装请求参数
try {
packageParam(params, httpPost);
@@ -265,13 +266,6 @@ public class HttpServiceImpl implements HttpService {
e.printStackTrace();
logger.error("请求过程出现异常: {}", e.getMessage());
return Msg.failed("请求过程出现异常: " + e.getMessage());
} finally {
// 释放资源
try {
release(httpClient);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -293,10 +287,10 @@ public class HttpServiceImpl implements HttpService {
}
@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(() -> {
try {
Msg<HttpEntity> msg = doPostWithEntity(url, headers, params);
Msg<HttpResponse> msg = doPostWithResponse(url, headers, params);
if (msg.getCode().equals(Msg.MSG_CODE_SUCCESS)) {
listener.onSuccess(msg);
} else if (msg.getCode().equals(Msg.MSG_CODE_FAILED)) {
@@ -316,18 +310,26 @@ public class HttpServiceImpl implements HttpService {
}
@Override
public Msg<HttpEntity> doPutWithEntity(String url) {
return doPutWithEntity(url, null);
public Msg<HttpResponse> doPutWithResponse(String url) {
return doPutWithResponse(url, null);
}
@Override
public Msg<String> doPut(String url, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doPutWithEntity(url, params);
return getStringMsg(httpEntityMsg);
Msg<HttpResponse> httpResponseMsg = doPutWithResponse(url, params);
String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
}
@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();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
@@ -342,41 +344,26 @@ public class HttpServiceImpl implements HttpService {
e.printStackTrace();
logger.error("请求过程出现异常: {}", e.getMessage());
return Msg.failed("网络请求时发生异常: " + e.getMessage());
} finally {
try {
release(httpClient);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String parseEntityToString(HttpEntity httpEntity) throws IOException {
return EntityUtils.toString(httpEntity, ENCODING);
}
private Msg<String> getStringMsg(Msg<HttpEntity> httpEntityMsg) {
if (Msg.MSG_CODE_SUCCESS.equals(httpEntityMsg.getCode())) {
try {
String result = parseEntityToString(httpEntityMsg.getData());
return Msg.success(httpEntityMsg.getMsg(), result);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串过程中发生异常:" + e.getMessage());
}
} else {
return Msg.failed(httpEntityMsg.getMsg());
}
}
@Override
public Msg<String> doDelete(String url) {
Msg<HttpEntity> httpEntityMsg = doDeleteWithEntity(url);
return getStringMsg(httpEntityMsg);
Msg<HttpResponse> httpResponseMsg = doDeleteWithResponse(url);
String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
}
@Override
public Msg<HttpEntity> doDeleteWithEntity(String url) {
public Msg<HttpResponse> doDeleteWithResponse(String url) {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
@@ -386,29 +373,30 @@ public class HttpServiceImpl implements HttpService {
} catch (Exception e) {
e.printStackTrace();
return Msg.failed("转换String时发生IO异常");
} finally {
try {
release(httpClient);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public Msg<String> doDelete(String url, Map<String, String> params) {
Msg<HttpEntity> httpEntityMsg = doDeleteWithEntity(url, params);
return getStringMsg(httpEntityMsg);
Msg<HttpResponse> httpResponseMsg = doDeleteWithResponse(url, params);
String stringResult;
try {
stringResult = EntityUtils.toString(httpResponseMsg.getData().getEntity());
return Msg.success("请求成功", stringResult);
} catch (IOException e) {
e.printStackTrace();
return Msg.failed("转换字符串失败:" + e.getMessage());
}
}
@Override
public Msg<HttpEntity> doDeleteWithEntity(String url, Map<String, String> params){
public Msg<HttpResponse> doDeleteWithResponse(String url, Map<String, String> params) {
if (params == null) {
params = new HashMap<>(0);
}
params.put("_method", "delete");
return doPostWithEntity(url, params);
return doPostWithResponse(url, params);
}
@@ -438,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;
try {
logger.info("执行请求:{},请求方式:{}", httpMethod.getURI().toString(), httpMethod.getMethod());
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
HttpEntity content;
if (httpResponse.getEntity() != null) {
content = httpResponse.getEntity();
return Msg.success(httpResponse.getStatusLine().getStatusCode() + "请求成功", content);
return Msg.success("请求成功", httpResponse);
}
}
} catch (IOException e) {
e.printStackTrace();
logger.error("请求过程中出现异常: {}", e.getMessage());
return Msg.failed("请求过程出现异常" + e.getMessage());
}
return Msg.failed(HttpStatus.SC_INTERNAL_SERVER_ERROR + "请求失败");
}

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>hxuanyu-spring-boot-starter-parent</artifactId>
<groupId>com.hxuanyu</groupId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -4,7 +4,7 @@
<groupId>com.hxuanyu</groupId>
<artifactId>hxuanyu-spring-boot-starter-parent</artifactId>
<version>1.0.4</version>
<version>1.0.5</version>
<name>hxuanyu-spring-boot-starter-parent</name>
<description>MonitorPushingParent</description>
<packaging>pom</packaging>
@@ -19,7 +19,7 @@
<connection>scm:git:https://git.hxuanyu.com/hxuanyu/hxuanyu-spring-boot-starter.git</connection>
<developerConnection>scm:git:https://git.hxuanyu.com/hxuanyu/hxuanyu-spring-boot-starter.git</developerConnection>
<url>https://git.hxuanyu.com/hxuanyu/hxuanyu-spring-boot-starter</url>
<tag>v1.0.4</tag>
<tag>v1.0.5</tag>
</scm>
<developers>
<developer>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>hxuanyu-spring-boot-starter-parent</artifactId>
<groupId>com.hxuanyu</groupId>
<version>1.0.4</version>
<version>1.0.5</version>
</parent>
<modelVersion>4.0.0</modelVersion>

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,14 +5,11 @@ import com.hxuanyu.network.service.HttpService;
import com.hxuanyu.test.MainApplication;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.web.WebAppConfiguration;
import static java.lang.Thread.sleep;
@SpringBootTest(classes = MainApplication.class)
public class NetworkTest {
@@ -24,7 +21,7 @@ public class NetworkTest {
@Test
@Timeout(3000)
public void testGet() throws InterruptedException {
public void testGet(){
Msg<String> msg = httpService.doGet("https://baidu.com");
logger.info("GET测试{}", msg);
assert msg.isSuccess();