Commit 3ed15d4d by 房斌

同上 增加了http协议传输

parent 690a2f81
......@@ -69,6 +69,14 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
......
......@@ -93,6 +93,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId>
</dependency>
</dependencies>
......
package com.secoo.mall.dubbo.spring.boot.autoconfigure;
package com.secoo.mall.gracefulshutdown.autoconfigure;
import com.secoo.mall.common.core.service.UpDatas;
import com.secoo.mall.common.util.string.StringUtil;
import com.secoo.mall.dubbo.monitor.config.ConfigCenter;
import com.secoo.mall.dubbo.monitor.dubbo.service.ProviderService;
import com.secoo.mall.dubbo.monitor.dubbo.service.RegistryServerSync;
import com.secoo.mall.dubbo.monitor.dubbo.service.impl.ProviderServiceImpl;
import com.secoo.mall.dubbo.service.GracefulShutDown;
import com.secoo.mall.dubbo.service.ShutDownDataReport;
import com.secoo.mall.dubbo.service.TomcatGracefulShutDown;
import com.secoo.mall.dubbo.service.impl.DubboCustomerShutDownHook;
import com.secoo.mall.dubbo.service.impl.TomcatShutDownHook;
import com.secoo.mall.gracefulshutdown.component.ShutDownDataReportAsyncHttp;
import com.secoo.mall.gracefulshutdown.monitor.config.ConfigCenter;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.exception.ConfigurationException;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.service.ProviderService;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.service.RegistryServerSync;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.service.impl.ProviderServiceImpl;
import com.secoo.mall.gracefulshutdown.monitor.utils.Tool;
import com.secoo.mall.gracefulshutdown.component.GracefulShutDown;
import com.secoo.mall.gracefulshutdown.component.ShutDownDataReport;
import com.secoo.mall.gracefulshutdown.component.TomcatGracefulShutDown;
import com.secoo.mall.gracefulshutdown.component.hook.DubboCustomerShutDownHook;
import com.secoo.mall.gracefulshutdown.component.hook.TomcatShutDownHook;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
@Configuration
......@@ -44,14 +52,15 @@ public class MatrixGracefulShutDownAutoConfiguration {
@ConditionalOnClass(ConfigCenter.class)
@DependsOn("configCenter")
UpDatas dubboUpdata(ConfigCenter configCenter) {
ShutDownDataReport transport= new ShutDownDataReport();
URL url =configCenter.formUrl(configCenter.registryAddress, configCenter.registryGroup, configCenter.username, configCenter.password,configCenter.timeout);
transport.setUrl(url);
if(StringUtil.isEmpty(configCenter.patch)){
configCenter.patch="/monitorZ";
}
transport.setPath(configCenter.patch);
return transport;
// ShutDownDataReport transport= new ShutDownDataReport();
// URL url =Tool.formUrl(configCenter.registryAddress, configCenter.registryGroup, configCenter.username, configCenter.password,configCenter.timeout);
// transport.setUrl(url);
// if(StringUtil.isEmpty(configCenter.patch)){
// configCenter.patch="/monitorZ";
// }
// transport.setPath(configCenter.patch);
ShutDownDataReportAsyncHttp report=new ShutDownDataReportAsyncHttp();
return report;
}
......@@ -77,8 +86,10 @@ public class MatrixGracefulShutDownAutoConfiguration {
@Bean
@ConditionalOnExpression("!T(org.springframework.util.StringUtils).isEmpty('${dubbo.registry.address:}')")
ConfigCenter configCenter(){
return new ConfigCenter();
ConfigCenter configCenter(Environment env){
ConfigCenter center= new ConfigCenter();
center.init(env);
return center;
}
......@@ -89,6 +100,7 @@ public class MatrixGracefulShutDownAutoConfiguration {
TomcatShutDownHook createServletConnectShoutDownHock() {
return new TomcatShutDownHook();
}
@Bean
@ConditionalOnClass(org.apache.catalina.connector.Connector.class)
@TomcatGracefulShutDownJudgmentInterface()
......@@ -96,15 +108,28 @@ public class MatrixGracefulShutDownAutoConfiguration {
return new TomcatGracefulShutDown(tomcatShutDownHook);
}
@Bean
@ConditionalOnExpression("!T(org.springframework.util.StringUtils).isEmpty('${dubbo.registry.address:}')")
public GracefulShutDown createGraceObject(UpDatas dubboUpdata) {
return new GracefulShutDown(dubboUpdata);
}
@Bean
@ConditionalOnBean(ConfigCenter.class)
@ConditionalOnExpression("!T(org.springframework.util.StringUtils).isEmpty('${dubbo.registry.address:}')")
Registry getRegistry(ConfigCenter configCenter) {
Registry registry = null;
URL registryUrl = null;
if (registryUrl == null) {
registryUrl = Tool.formUrl(configCenter.getRegistryAddress(), configCenter.getRegistryGroup(), configCenter.getUsername(), configCenter.getPassword(), configCenter.getTimeout());
// registryUrl.setPath(patch);
}
RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
registry = registryFactory.getRegistry(registryUrl);
return registry;
}
......
package com.secoo.mall.dubbo.spring.boot.autoconfigure;
package com.secoo.mall.gracefulshutdown.autoconfigure;
import com.secoo.mall.dubbo.condition.TomcatGracefulShutDownJudgment;
import com.secoo.mall.gracefulshutdown.condition.TomcatGracefulShutDownJudgment;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.*;
......
package com.secoo.mall.dubbo.service;
package com.secoo.mall.gracefulshutdown.component;
import com.alibaba.fastjson.JSON;
import com.secoo.mall.common.core.bean.gracefulshowtdownBean.ExecutorDetail;
......@@ -7,8 +7,8 @@ import com.secoo.mall.common.core.service.StopService;
import com.secoo.mall.common.core.service.UpDatas;
import com.secoo.mall.common.util.date.DateUtil;
import com.secoo.mall.common.util.log.LoggerUtil;
import com.secoo.mall.dubbo.monitor.utils.Tool;
import com.secoo.mall.dubbo.service.impl.TomcatShutDownHook;
import com.secoo.mall.gracefulshutdown.monitor.utils.Tool;
import com.secoo.mall.gracefulshutdown.component.hook.TomcatShutDownHook;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.DubboShutdownHook;
import org.apache.dubbo.config.spring.extension.SpringExtensionFactory;
......@@ -42,7 +42,7 @@ public class GracefulShutDown implements CommandLineRunner, ApplicationListener<
//容器初始化后执行
@Override
public void run(String... args) throws Exception {
logger.info("dddddddddddddduuuuuuuuuuuuuuuuubbbbbbbbbbbboooooooooooolllllllllll!!!!");
logger.info("dddddddddddddduuuuuuuuuuuuuuuuubbbbbbbbbbbboooooooooooolllllllllllme!!!!");
if (DubboShutdownHook.getDubboShutdownHook() != null) {
//hock卸载
DubboShutdownHook.getDubboShutdownHook().unregister();
......@@ -56,7 +56,6 @@ public class GracefulShutDown implements CommandLineRunner, ApplicationListener<
public void test() {
logger.info("222222222222 closeevent");
ExecutorDetails result = new ExecutorDetails();
result.setCode(0);
List<ExecutorDetail> details = new ArrayList<ExecutorDetail>();
......@@ -65,7 +64,7 @@ public class GracefulShutDown implements CommandLineRunner, ApplicationListener<
String name = ApplicationModel.getApplication();
result.setIp(ip);
result.setName(name);
logger.info("GracefulShutDown execute:name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
logger.info("gracefulshutdown execute:name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
try {
......@@ -92,20 +91,19 @@ public class GracefulShutDown implements CommandLineRunner, ApplicationListener<
}
} catch (Exception e) {
LoggerUtil.error("matrix.GracefulShutDown.error", e);
LoggerUtil.error("matrix.gracefulshutdown.error", e);
}
try {
dubboUpdata.upData(result);
} catch (Exception e) {
LoggerUtil.error("matrix.GracefulShutDown update .error data:" + JSON.toJSONString(result), e);
LoggerUtil.error("matrix.gracefulshutdown update .error data:" + JSON.toJSONString(result), e);
}
logger.info("GracefulShutDown execute end :name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
logger.info("gracefulshutdown execute end :name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
}
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
logger.info("222222222222 closeevent");
ExecutorDetails result = new ExecutorDetails();
result.setCode(0);
List<ExecutorDetail> details = new ArrayList<ExecutorDetail>();
......@@ -114,7 +112,7 @@ public class GracefulShutDown implements CommandLineRunner, ApplicationListener<
String name = ApplicationModel.getApplication();
result.setIp(ip);
result.setName(name);
logger.info("GracefulShutDown execute:name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
logger.info("gracefulshutdown execute:name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
try {
......@@ -141,21 +139,21 @@ public class GracefulShutDown implements CommandLineRunner, ApplicationListener<
}
} catch (Exception e) {
LoggerUtil.error("matrix.GracefulShutDown.error", e);
LoggerUtil.error("matrix.gracefulshutdown.error", e);
}
try {
dubboUpdata.upData(result);
} catch (Exception e) {
LoggerUtil.error("matrix.GracefulShutDown update .error data:" + JSON.toJSONString(result), e);
LoggerUtil.error("matrix.gracefulshutdown update .error data:" + JSON.toJSONString(result), e);
}
logger.info("GracefulShutDown execute end :name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
logger.info("gracefulshutdown execute end :name:" + name + " ip:" + ip + " time:" + DateUtil.getDateTime());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
logger.info("222222222222 setContext");
}
@Override
......
package com.secoo.mall.dubbo.service;
package com.secoo.mall.gracefulshutdown.component;
import com.alibaba.fastjson.JSON;
import com.secoo.mall.common.core.service.UpDatas;
......@@ -11,7 +11,6 @@ import org.apache.dubbo.remoting.zookeeper.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
public class ShutDownDataReport implements UpDatas<ExecutorDetails> {
......@@ -47,6 +46,8 @@ public class ShutDownDataReport implements UpDatas<ExecutorDetails> {
// String monitor = "/monitorZ/" + obj.getName() + "/" + obj.getIp();
logger.info("ShutDownDataReport sendData: path:"+monitor+" data:"+ JSON.toJSONString(obj));
cliet.create(monitor, JSON.toJSONString(obj), true);
String contest= cliet.getContent(monitor);
logger.info("result-------->"+contest);
} catch (Exception e) {
LoggerUtil.info("Exception e:" ,e);
}
......
package com.secoo.mall.dubbo.service;
package com.secoo.mall.gracefulshutdown.component;
import com.secoo.mall.dubbo.service.impl.TomcatShutDownHook;
import com.secoo.mall.gracefulshutdown.component.hook.TomcatShutDownHook;
import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......
package com.secoo.mall.dubbo.service.impl;
package com.secoo.mall.gracefulshutdown.component.hook;
import com.secoo.mall.common.util.date.DateUtil;
import com.secoo.mall.common.util.string.StringUtil;
import com.secoo.mall.common.core.bean.gracefulshowtdownBean.ExecutorDetail;
import com.secoo.mall.dubbo.service.AbstractShutDown;
import com.secoo.mall.gracefulshutdown.component.AbstractShutDown;
import org.apache.catalina.connector.Connector;
import java.util.ArrayList;
import java.util.List;
......
package com.secoo.mall.dubbo.condition;
package com.secoo.mall.gracefulshutdown.condition;
import com.secoo.mall.dubbo.monitor.config.ConfigCenter;
import com.secoo.mall.gracefulshutdown.monitor.config.ConfigCenter;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.springframework.boot.SpringBootVersion;
......@@ -11,14 +11,14 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
public class TomcatGracefulShutDownJudgment implements Condition {
public static final Logger logger = LoggerFactory.getLogger(ConfigCenter.class);
public static volatile boolean flag = true;
public static boolean flag = true;
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
String version=SpringBootVersion.getVersion();
logger.info("springboot version:"+version);
if (!flag) {//非servlet 环境 直接返回
if (!flag) {//非tomcat 环境 直接返回
return false;
}
try {
......
......@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.secoo.mall.dubbo.monitor.dubbo.service;
package com.secoo.mall.gracefulshutdown.monitor.dubbo.service;
import java.util.List;
/**
......
package com.secoo.mall.dubbo.monitor.dubbo.service;
package com.secoo.mall.gracefulshutdown.monitor.dubbo.service;
import com.alibaba.fastjson.JSON;
import com.secoo.mall.common.util.string.StringUtil;
import com.secoo.mall.dubbo.monitor.dubbo.Constants.Constants;
import com.secoo.mall.dubbo.monitor.utils.CoderUtil;
import com.secoo.mall.dubbo.monitor.utils.Stack;
import com.secoo.mall.dubbo.monitor.utils.Tool;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.Constants.Constants;
import com.secoo.mall.gracefulshutdown.monitor.utils.CoderUtil;
import com.secoo.mall.gracefulshutdown.monitor.utils.Stack;
import com.secoo.mall.gracefulshutdown.monitor.utils.Tool;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.NotifyListener;
......
package com.secoo.mall.dubbo.monitor.dubbo.service.impl;
package com.secoo.mall.gracefulshutdown.monitor.dubbo.service.impl;
import com.secoo.mall.common.util.string.StringUtil;
import com.secoo.mall.dubbo.monitor.dubbo.Constants.Constants;
import com.secoo.mall.dubbo.monitor.dubbo.service.ProviderService;
import com.secoo.mall.dubbo.monitor.dubbo.service.RegistryServerSync;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.Constants.Constants;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.service.ProviderService;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.service.RegistryServerSync;
import org.apache.dubbo.common.URL;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
......@@ -15,7 +14,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
@Service
public class ProviderServiceImpl extends AbstractService implements ProviderService {
public ProviderServiceImpl(RegistryServerSync sync) {
super(sync);
......
package com.secoo.mall.dubbo.monitor.utils;
package com.secoo.mall.gracefulshutdown.monitor.utils;
import com.secoo.mall.dubbo.condition.TomcatGracefulShutDownJudgment;
import com.secoo.mall.gracefulshutdown.condition.TomcatGracefulShutDownJudgment;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
......
package com.secoo.mall.dubbo.monitor.utils;
package com.secoo.mall.gracefulshutdown.monitor.utils;
import java.io.IOException;
import java.io.PrintWriter;
......
......@@ -14,12 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.secoo.mall.dubbo.monitor.utils;
package com.secoo.mall.gracefulshutdown.monitor.utils;
import com.secoo.mall.common.util.string.StringUtil;
import com.secoo.mall.gracefulshutdown.monitor.dubbo.Constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.spring.extension.SpringExtensionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.lang.reflect.Field;
......@@ -72,4 +73,24 @@ public class Tool {
return null;
}
public static URL formUrl(String config, String group, String username, String password, String timeout) {
URL url = URL.valueOf(config);
if (StringUtils.isNotEmpty(group)) {
url = url.addParameter(Constants.GROUP_KEY, group);
}
if(StringUtil.isEmpty(timeout)){
url=url.addParameter("timeout",20000);
}else{
url=url.addParameter("timeout", Integer.valueOf(timeout).intValue());
}
if (StringUtils.isNotEmpty(username)) {
url = url.setUsername(username);
}
if (StringUtils.isNotEmpty(password)) {
url = url.setPassword(password);
}
return url;
}
}
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.secoo.mall.dubbo.spring.boot.autoconfigure.MatrixGracefulShutDownAutoConfiguration,\
com.secoo.mall.dubbo.monitor.config.ConfigCenter
com.secoo.mall.gracefulshutdown.autoconfigure.MatrixGracefulShutDownAutoConfiguration
org.springframework.context.ApplicationContextInitializer=\
com.secoo.mall.dubbo.monitor.utils.SpringContextHolder
\ No newline at end of file
com.secoo.mall.gracefulshutdown.monitor.utils.SpringContextHolder
\ No newline at end of file
package com.secoo.mall.dubbo.monitor.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* httpClient封装
*
* @author QIANG
*/
public class HttpClientUtils {
private static Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int CONNECT_TIMEOUT = 100000;
private static final int SOCKET_TIMEOUT = 100000;
private static final int REQUEST_TIMEOUT = 2000;
private static final String CHARSET = "UTF-8";
static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(300);
connMgr.setDefaultMaxPerRoute(300);
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 请求超时时间
configBuilder.setConnectTimeout(CONNECT_TIMEOUT);
// 连接不够时等待超时时间,不设置将阻塞线程
configBuilder.setConnectionRequestTimeout(REQUEST_TIMEOUT);
// 等待数据超时时间
configBuilder.setSocketTimeout(SOCKET_TIMEOUT);
LOG.debug("Http参数设置,连接超时时间[{}],Socket超时时间[{}],请求超时时间[{}]", CONNECT_TIMEOUT, SOCKET_TIMEOUT);
requestConfig = configBuilder.build();
}
/**
* 设置连接超时和请求超时
*
* @param connectTimeout
* @param socketTimeout
* @param connectionRequestTimeout
*/
public static void setHttpParam(int connectTimeout, int socketTimeout, int connectionRequestTimeout) {
RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(connectTimeout);
configBuilder.setSocketTimeout(socketTimeout);
configBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
LOG.debug("Http参数自定义设置,请求超时时间[{}],等待数据超时时间[{}],连接不够时等待超时时间[{}]", connectTimeout, socketTimeout,
connectionRequestTimeout);
requestConfig = configBuilder.build();
}
/**
* 发送 GET 请求(HTTP),不带输入数据
*
* @param url
* @return
* @throws Exception
*/
public static String doGet(String url) {
try {
String result = doGet(url, new HashMap<>(10));
return result;
} catch (Exception e) {
LOG.error("发送 GET 请求ERROR :{}", e);
}
return "";
}
/**
* 发送 GET 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
* @throws Exception
*/
public static String doGet(String url, Map<String, Object> params) throws Exception {
return doGet(url, params, CHARSET, new HashMap<>(16));
}
public static String doGet(String url, Map<String, Object> params, String charset, Map<String, String> headers) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.debug("warn:doGet url is null or '' ");
return result;
}
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connMgr).build();
CloseableHttpResponse response = null;
InputStream instream = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setCharset(Charset.forName(StringUtils.isEmpty(charset) ? CHARSET : charset));
uriBuilder.addParameters(pairList);
URI uri = uriBuilder.build();
HttpGet httpGet = new HttpGet(uri);
headers.entrySet().forEach(entry -> {
httpGet.setHeader(entry.getKey(), entry.getValue());
});
response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, charset);
}
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
LOG.debug("close instream response httpClient connection succ");
}
return result;
}
public static HttpEntity doGetByDefault(String url) throws Exception {
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connMgr).build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpGet);
LOG.info("doGet statusCode:{}", response.getStatusLine().getStatusCode());
return response.getEntity();
}
public static String doDelete(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connMgr).build();
CloseableHttpResponse response = null;
InputStream instream = null;
List<NameValuePair> pairList = new ArrayList<>(params.size());
params.entrySet().forEach(entry -> {
pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
});
try {
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setCharset(Charset.forName(CHARSET));
uriBuilder.addParameters(pairList);
URI uri = uriBuilder.build();
HttpDelete httpDelete = new HttpDelete(uri);
headers.entrySet().forEach(entry -> {
httpDelete.setHeader(entry.getKey(), entry.getValue());
});
response = httpclient.execute(httpDelete);
LOG.info("httpDelete statusCode:{}", response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
return IOUtils.toString(instream, CHARSET);
}
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
LOG.debug("close instream response httpClient connection succ");
}
return "";
}
/**
* 发送 PUT 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
* @throws Exception
*/
public static String doPut(String url, Map<String, Object> params, String charset, Map<String, String> headers, String body) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
return result;
}
List<NameValuePair> pairList = new ArrayList<>(params.size());
params.entrySet().forEach(entry -> {
pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
});
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connMgr).build();
CloseableHttpResponse response = null;
InputStream instream = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setCharset(Charset.forName(StringUtils.isEmpty(charset) ? CHARSET : charset));
uriBuilder.addParameters(pairList);
URI uri = uriBuilder.build();
HttpPut httpPut = new HttpPut(uri);
if (!StringUtils.isEmpty(body)) {
httpPut.setEntity(new StringEntity(body, "UTF-8"));
}
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
}
}
response = httpclient.execute(httpPut);
LOG.info("doGet statusCode:{}", response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, charset);
}
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
LOG.debug("close instream response httpClient connection succ");
}
return result;
}
/**
* 发送 POST 请求(HTTP),不带输入数据
*
* @param url
* @return
* @throws Exception
*/
public static String doPost(String url) throws Exception {
return doPost(url, new HashMap<>(16));
}
/**
* 发送 POST 请求(HTTP),K-V形式
*
* @param url API接口URL
* @param params 参数map
* @return
* @throws Exception
*/
public static String doPost(String url, Map<String, Object> params) throws Exception {
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPost url is null or '' ");
return null;
}
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(CHARSET)));
return send(httpPost, false);
}
/**
* 发送 POST 请求(HTTP),xml
*
* @param url API接口URL
* @param xml xml 参数
* @return
* @throws Exception
*/
public static String doPost(String url, String xml) throws Exception {
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPost url is null or '' ");
return null;
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(xml, "GBK"));
return send(httpPost, false);
}
/**
* 发送 POST 请求(HTTP),JSON形式
*
* @param url
* @param json json对象
* @return
* @throws Exception
*/
public static String doPost(String url, Object json) throws Exception {
if (StringUtils.isEmpty(url)) {
LOG.error("warn:doPostByJson url is null or '' ");
return null;
}
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(json.toString(), CHARSET);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
return send(httpPost, false);
}
public static String doPost(String url, HttpEntity entity, Map<String, String> headers) throws Exception {
if (StringUtils.isEmpty(url)) {
LOG.error("warn:doPostByJson url is null or '' ");
return null;
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
headers.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
return send(httpPost, false);
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
*
* @param apiUrl API接口URL
* @param params 参数map
* @return
* @throws Exception
*/
public static String doPostSsl(String apiUrl, Map<String, Object> params) throws Exception {
if (StringUtils.isEmpty(apiUrl)) {
LOG.info("warn:doPostSSL url is null or '' ");
return null;
}
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
return send(httpPost, true);
}
/**
* 发送 SSL POST 请求(HTTPS),JSON形式
*
* @param apiUrl API接口URL
* @param json JSON对象
* @return
* @throws Exception
*/
public static String doPostSsl(String apiUrl, Object json) throws Exception {
if (StringUtils.isEmpty(apiUrl)) {
LOG.info("warn:doPostSSL By Json url is null or '' ");
return null;
}
StringEntity stringEntity = new StringEntity(json.toString(), CHARSET);
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setEntity(stringEntity);
stringEntity.setContentEncoding(CHARSET);
stringEntity.setContentType("application/json");
return send(httpPost, true);
}
/**
* 发送Post请求
*
* @param httpPost
* @return
* @throws IOException
* @throws ClientProtocolException
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private static String send(HttpPost httpPost, boolean isSsl) throws ClientProtocolException, IOException,
KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
CloseableHttpClient httpClient = null;
InputStream instream = null;
String result = null;
CloseableHttpResponse response = null;
try {
if (isSsl) {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
httpClient = HttpClients.custom().setConnectionManager(connMgr).setSSLSocketFactory(sslsf)
.setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(connMgr)
.build();
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, CHARSET);
}
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
LOG.debug("close instream response httpClient connection succ");
}
return result;
}
public static void checkResult(String result,String codeMsg){
JSONObject data = JSON.parseObject(result);
int resultCode = data.getInteger(StringUtils.isEmpty(codeMsg)?"errcode":codeMsg);
if (resultCode != 0) {
LOG.error("send http resultCode not 0,result:{}", result);
}
}
}
......@@ -252,6 +252,11 @@
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment