import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 服务器端请求服务类
*
* @author Administrator
* @date 2018年1月15日
* @version 1.0
*/
@SuppressWarnings("deprecation")
public abstract class RequestService {
/** jackJson 转化工具 **/
private static final ObjectMapper mapper = new ObjectMapper();
/** 连接池配置 **/
private static PoolingHttpClientConnectionManager connMgr;
/** requestConfig **/
private static RequestConfig requestConfig; /** 日志 **/
private static Logger logger = LoggerFactory.getLogger(RequestService.class);
/** 服务器地址 **/
private static final String HOST_PATH = H5FileUtils.getValueFromProperties("remote.server.host");
/** 连接超时 **/
private static final int CONNECTION_TIMEOUT = NumberUtils.toInt(H5FileUtils.getValueFromProperties("remote.conntection.timeout")) * 1000; static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(CONNECTION_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(CONNECTION_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(CONNECTION_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
} /**
* GET方式请求远端服务器数据
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
@SuppressWarnings("rawtypes")
protected ResponseVO getRemoteReqData(String url){
logger.debug(">>>getRemoteReqData(String url)");
logger.debug("url:" + url);
return this.getRemoteReqData(url, null);
} /**默认采用不解码形式
* GET方式请求远端服务器数据
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
@SuppressWarnings("rawtypes")
protected ResponseVO getRemoteReqData(String url, String specifyUrl) {
logger.debug(">>>getRemoteReqData(String url, String specifyUrl)");
logger.debug("url:" + url);
logger.debug("specifyUrl:" + specifyUrl);
return this.getRemoteReqData(url, specifyUrl, CommonConstants.DECODE_N);
} /**
* GET方式请求远端服务器数据
* @param url
* @return ResponseVO
* @throws IOException
* @throws ClientProtocolException
*/
@SuppressWarnings("rawtypes")
protected ResponseVO getRemoteReqData(String url, String specifyUrl, String isDecode) {
logger.debug(">>>getRemoteReqData(String url, String specifyUrl, String isDecode)");
logger.debug("url:" + url);
logger.debug("specifyUrl:" + specifyUrl);
logger.debug("isDecode:" + isDecode);
// 开启服务
CloseableHttpClient client = getHttpClients(specifyUrl); // 主库判断
if(StringUtils.isNotEmpty(specifyUrl)){
url = specifyUrl + url;
}else{
url = getHostUrl() + url;
}
logger.debug("-> getUrl:" + url);
HttpGet get = new HttpGet(url);
ResponseVO respVO = null;
try {
HttpResponse response=client.execute(get);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
HttpEntity entity=response.getEntity();
String returnValue = EntityUtils.toString(entity,CommonConstants.CHARSET_DEFAULT);
// 解码判断
if(StringUtils.equals(isDecode, CommonConstants.DECODE_Y)){
returnValue = URLDecoder.decode(returnValue, CommonConstants.CHARSET_DEFAULT);
}
logger.debug("->getRequest:returnValue from remoteUrl: " + returnValue);
respVO = mapper.readValue(returnValue, ResponseVO.class);
}else if(HttpStatus.SC_NO_CONTENT==response.getStatusLine().getStatusCode()){
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程连接未能接通!");
}else if(HttpStatus.SC_NOT_FOUND==response.getStatusLine().getStatusCode()){
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程连接地址未找到!");
}else if(HttpStatus.SC_BAD_REQUEST ==response.getStatusLine().getStatusCode()) {
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程接口需求数据与本地数据不匹配!");
}
} catch (ClientProtocolException e) {
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程连接出现错误!");
e.printStackTrace();
} catch (IOException e) {
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程端口出现错误!");
e.printStackTrace();
}
logger.debug("<<<getRemoteReqData(String url, String specifyUrl, String isDecode)");
return respVO;
} /**
* GET方式请求远端服务器流,
* 因返回InputStream输入流,因此一定要try catch,关闭
* @param url
* @return InputStream
* @throws IOException
* @throws ClientProtocolException
*/
protected InputStream getRemoteReqStream(String url) throws ClientProtocolException, IOException{
logger.debug(">>>getRemoteReqStream(String url)");
logger.debug("url:" + url);
return getRemoteReqStream(url, null);
}
/**
* GET方式请求远端服务器流,
* 因返回InputStream输入流,因此一定要try catch,关闭
* @param url
* @return InputStream
* @throws IOException
* @throws ClientProtocolException
*/
protected InputStream getRemoteReqStream(String url, String specifyUrl) throws ClientProtocolException, IOException{
logger.debug(">>>getRemoteReqStream(String url, String specifyUrl)");
logger.debug("url:" + url);
logger.debug("specifyUrl:" + specifyUrl);
// 主库判断
if(StringUtils.isNotEmpty(specifyUrl)){
url = specifyUrl + url;
}else{
url = getHostUrl() + url;
}
logger.debug("-> getStreamUrl:" + url);
// 开启服务
CloseableHttpClient client = getHttpClients(specifyUrl);
HttpGet get=new HttpGet(url);
InputStream is = null;
HttpResponse response=client.execute(get);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
HttpEntity entity=response.getEntity();
is = entity.getContent();
}
logger.debug("<<<getRemoteReqStream(String url, String specifyUrl)");
return is;
} /**
* POST方式请求远端服务器数据
* @param url
* @return ResponseVO
*/
@SuppressWarnings("rawtypes")
protected ResponseVO postRemoteReqData(String url, HttpEntity entity){
logger.debug(">>>postRemoteReqData(String url, HttpEntity entity)");
logger.debug("url:" + url);
logger.debug("entity:{}", entity);
return postRemoteReqData(url, entity, null);
}
/**
* 默认此方法不采用解码形式
* POST方式请求远端服务器数据
* @param url
* @return ResponseVO
*/
@SuppressWarnings("rawtypes")
protected ResponseVO postRemoteReqData(String url, HttpEntity entity, String specifyUrl){
logger.debug(">>>postRemoteReqData(String url, HttpEntity entity)");
logger.debug("url:" + url);
logger.debug("entity:{}", entity);
logger.debug("specifyUrl:" + specifyUrl);
return postRemoteReqData(url, entity, specifyUrl, CommonConstants.DECODE_N);
} /**
* post请求
* @param rEMOTE_URL_GESTURE_SAVE
* @param createParams
* @param specifyUrl(指定url)
* @return ResponseVO
*/
@SuppressWarnings({"rawtypes"})
public ResponseVO postRemoteReqData(String url, HttpEntity entity, String specifyUrl, String isDecode) {
logger.debug(">>>postRemoteReqData(String url, HttpEntity entity, String specifyUrl, String isDecode)");
logger.debug("url:" + url);
logger.debug("entity:{}", entity);
logger.debug("specifyUrl:" + specifyUrl);
logger.debug("isDecode:" + isDecode);
// 主库判断
if(StringUtils.isNotEmpty(specifyUrl)){
url = specifyUrl + url;
}
else{
url = getHostUrl() + url;
}
logger.debug("-> postUrl:" + url);
// 开启服务
CloseableHttpClient client = getHttpClients(specifyUrl);
//POST的URL
HttpPost httpPost = new HttpPost(url);
// 返回值
ResponseVO respVO = null;
//添加参数
httpPost.setEntity(entity);
HttpResponse response;
try {
response = client.execute(httpPost); if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
String returnValue = EntityUtils.toString(response.getEntity(),CommonConstants.CHARSET_DEFAULT);
// 解码判断
if(StringUtils.equals(isDecode, CommonConstants.DECODE_Y)){
returnValue = URLDecoder.decode(returnValue, CommonConstants.CHARSET_DEFAULT);
}
logger.debug("->getRequest:returnValue from remoteUrl: " + returnValue);
respVO = mapper.readValue(returnValue, ResponseVO.class);
}else if(HttpStatus.SC_NO_CONTENT==response.getStatusLine().getStatusCode()){
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程连接未能接通!");
}else if(HttpStatus.SC_NOT_FOUND==response.getStatusLine().getStatusCode()){
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程连接地址未找到!");
}else if(HttpStatus.SC_BAD_REQUEST ==response.getStatusLine().getStatusCode()) {
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程接口需求数据与本地数据不匹配!");
}
} catch (ClientProtocolException e) {
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程连接出现错误!");
e.printStackTrace();
} catch (IOException e) {
respVO = new ResponseVO();
respVO.setResponseCode("-1");
respVO.setResponseMessage("远程端口出现错误!");
e.printStackTrace();
}
logger.debug("respVO:{}", respVO);
logger.debug("<<<postRemoteReqData(String url, HttpEntity entity, String specifyUrl, String isDecode)");
return respVO;
} /**
* 构建Request的Post String参数
* @param names String[]
* @param values String[]
* @return HttpEntity
* @throws UnsupportedEncodingException
*/
protected HttpEntity createParams(String[] names, String[] values) {
logger.debug(">>>createParams(String[] names, String[] values)");
logger.debug("names:{}", names.toString());
logger.debug("values:{}", values.toString());
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
HttpEntity entity = null;
for(int i = 0; i < names.length; i++){
paramsList.add(new BasicNameValuePair(names[i], values[i]));
}
try{
entity = new UrlEncodedFormEntity(paramsList, CommonConstants.CHARSET_DEFAULT);
}catch(UnsupportedEncodingException e){
logger.debug("->UnsupportedEncodingException:", e);
}
logger.debug("paramsList:{}", paramsList);
logger.debug("<<<createParams(String[] names, String[] values)");
return entity;
} /**
* 构建Request的Post Json格式对象参数
* @throws UnsupportedEncodingException
*/
protected HttpEntity createJsonParams(Object jsonObject) {
logger.debug(">>> createJsonParams(Object jsonObject)");
logger.debug("jsonObject:{}", jsonObject);
StringEntity entity = null;
try{
entity = new StringEntity(H5Utils.mapper.writeValueAsString(jsonObject), CommonConstants.CHARSET_DEFAULT);
entity.setContentEncoding(CommonConstants.CHARSET_DEFAULT);
entity.setContentType("application/json");
} catch (JsonProcessingException e) {
logger.debug("->JsonProcessingException:", e);
}
logger.debug("entity:{}", entity);
logger.debug("<<<createJsonParams(Object jsonObject)");
return entity;
} /**
* 获取服务地址
* @return
*/
private String getHostUrl(){
logger.debug(">>>getHostUrl()");
String url = HOST_PATH;
logger.debug("url:" + url);
logger.debug("<<<getHostUrl()");
return url;
} /**
* 根据http请求或者https请求,获取httpClients
* @return
*/
private CloseableHttpClient getHttpClients(String specifyUrl) {
logger.debug(">>>getHttpClients(String specifyUrl)");
logger.debug("specifyUrl:" + specifyUrl);
// https问题
CloseableHttpClient httpClient = null;
if(StringUtils.isNotEmpty(specifyUrl) && specifyUrl.indexOf("https:") > 0){
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
}else{
httpClient = HttpClients.custom().setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
logger.debug("provIp: " + specifyUrl);
}
logger.debug("<<<getHttpClients(String specifyUrl)");
return httpClient;
} /**
* 转化List为对象List
* @param class1
* @return
*/
@SuppressWarnings("rawtypes")
protected List<?> convertListToObject(List originalList,Class<?> class1) {
logger.debug(">>>convertListToObject(List originalList,Class<?> class1)");
logger.debug("originalList:{}", originalList);
logger.debug("class1:{}", class1);
List<Object> list = null;
try{
if(!CollectionUtils.isEmpty(originalList)){
list = new ArrayList<Object>();
for(Object obj : originalList){
Object target = class1.newInstance();
BeanUtils.copyProperties(target, obj);
list.add(target);
}
}
} catch(Exception e){
e.printStackTrace();
list = null;
}
logger.debug("<<<convertListToObject(List originalList,Class<?> class1)");
return list;
} /**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
logger.debug(">>>createSSLConnSocketFactory()");
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
} @Override
public void verify(String host, SSLSocket ssl) throws IOException {
} @Override
public void verify(String host, X509Certificate cert) throws SSLException {
} @Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
logger.debug("sslsf:{}", sslsf);
logger.debug("<<<createSSLConnSocketFactory()");
return sslsf;
} }

简单的remote Request:

        HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// 请求超时
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
post.addHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
post.setEntity(entity);
try {
client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

remote Request的更多相关文章

  1. Adaptively handling remote atomic execution based upon contention prediction

    In one embodiment, a method includes receiving an instruction for decoding in a processor core and d ...

  2. Java基础常见英语词汇

    Java基础常见英语词汇(共70个) ['ɔbdʒekt] ['ɔ:rientid]导向的                             ['prəʊɡræmɪŋ]编程 OO: object ...

  3. IT软件开发常用英语词汇

    Aabstract 抽象的abstract base class (ABC)抽象基类abstract class 抽象类abstraction 抽象.抽象物.抽象性access 存取.访问access ...

  4. computer English

    算法常用术语中英对照Data Structures 基本数据结构Dictionaries 字典PriorityQueues 堆Graph Data Structures 图Set Data Struc ...

  5. A javascript library providing cross-browser, cross-site messaging/method invocation. http://easyxdm.net

    easyXDM - easy Cross-Domain Messaging easyXDM is a Javascript library that enables you as a develope ...

  6. [Web] What Is JSONP?

    JSONP—or JSON with padding—is a sneaky technique that web developers came up with to work around the ...

  7. nginx整合tomcat集群并做session共享----测试案例

    最近出于好奇心,研究了一下tomcat集群配置,并整合nginx,实现负载均衡,session共享,写篇记录,防止遗忘.---------菜鸡的自我修炼. 说明:博主采用一个web项目同时部署到两台t ...

  8. js实现省市区联动

    先来看看效果图吧,嘻嘻~~~~~~~~~~~~~~~~~~~· 代码在下面: 示例一: html: <!DOCTYPE html> <html> <head> &l ...

  9. IBM flex system P260

    CMM 机箱管理模块 提供如下功能: 电力控制 风扇管理 机箱和计算节点初始化 交换机管理 诊断:机箱.IO选项和计算节点 资源发现和库存管理 资源告警和监控 机箱和计算节点的电源管理 安全策略管理 ...

随机推荐

  1. prisma 集成 pipelinedb测试

    pipelinedb 是一个基于pg数据库开发的stream sql 数据库,和prisma 集成起来可以开发很 方便的stream 应用 使用docker 安装 项目初始化 prisma init ...

  2. TensorFlow入门教程集合

    TensorFlow入门教程之0: BigPicture&极速入门 TensorFlow入门教程之1: 基本概念以及理解 TensorFlow入门教程之2: 安装和使用 TensorFlow入 ...

  3. 在服务端处理同步发送小消息的性能上Kafka>RocketMQ>RabbitMQ

    在发送小消息的场景中,三个消息中间件的表现区分明显: Kafka的吞吐量高达17.3w/s,远超其他两个产品.这主要取决于它的队列模式保证了写磁盘的过程是线性IO.此时broker磁盘IO已达瓶颈. ...

  4. Arrays、ArrayUtils 区别

    Arrays java.util 包提供的静态类:java.util.Arrays 此静态类专门用来操作array ,提供搜索.排序.复制等静态方法. ArrayUtils apache 提供的类:o ...

  5. 什么是Asp.net Core?和 .net core有什么区别?(转)

    什么是Asp.Net core 我相信很多C# Developer已经对于.net core不算陌生了,就算没有正式使用相信也应该有所了解.微软在推出来.net core的同时为了方便一些原有的项目可 ...

  6. golang sizeof 占用空间大小

    C语言中,可以使用sizeof()计算变量或类型占用的内存大小.在Go语言中,也提供了类似的功能, 不过只能查看变量占用空间大小.具体使用举例如下. package main import ( &qu ...

  7. 【python】常用的一些内置函数

    1.cmp cmp(A,B)函数,比较A,B的大小,如果A大于B,返回1,A小于B返回-1,A等于B返回0 print cmp(12,33) >>>-1 print cmp(&quo ...

  8. [记录]js跨域调用mvc ActionResult扩展

    背景 最近2个项目中都用到了js跨域访问的知识,2个项目都需要主站与各个分站之间进行数据交互.状态同步等相关操作.浏览器本身是不允许进行跨域访问,在MVC中我们可以扩展一个方法来实现这个功能.在此大家 ...

  9. Kubernetes集群安全配置案例

    Kubernetes 系统提供了三种认证方式:CA 认证.Token 认证 和 Base 认证.安全功能是一把双刃剑,它保护系统不被攻击,但是也带来额外的性能损耗.集群内的各组件访问 API Serv ...

  10. git如何查看某个人提交的日志。

    我们知道,在git进行cherry-pick的时候,找到commit id是至关重要, 如果我们是很多人在一个分支开发,开发完了之后,发现某个人的功能,需要单独cherry-pick到另外一分支上去. ...