重新传输的Controller实现
@RequestMapping(value = "/retransmissionByPlanId",method = RequestMethod.GET)
@ApiOperation("通过计划id重新传输")
public ServiceResult retransmissionByPlanId(String planId){
// 确认下流程
return planService.retransmissionByPlanId(planId);
}
批量重新传输的Controller实现
@RequestMapping(value = "/retransmissionByPlanIdBatch",method = RequestMethod.POST)
@ApiOperation("批量通过计划id重新传输")
public ServiceResult retransmissionByPlanIdBatch(@RequestBody String [] planIdArray){
// 确认下流程
return planService.retransmissionByPlanIdBatch(planIdArray);
}
重新传输的 ServiceImpl 实现
@Override
public ServiceResult retransmissionByPlanId(String planId) {
ServiceResult result = new ServiceResult(false);
Map param = new HashMap<>();
param.put("planID",planId);
List
Config工具类
package cn.piesat.sar.base;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class Config {
// @Value("${account.url}")
// private String authUrl;
@Value("${mq.api}")
private String mqApi;
}
clientConfiguration工具类
package cn.piesat.sar.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.http.*;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.cookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.*;
import org.apache.http.conn.HttpConnectionFactory;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.HttpMessageParserFactory;
import org.apache.http.io.HttpMessageWriterFactory;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.BasicNamevaluePair;
import org.apache.http.message.LineParser;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
@Component
public class ClientConfiguration {
private final Logger logger = LoggerFactory.getLogger(ClientConfiguration.class);
CloseableHttpClient httpclient;
PoolingHttpClientConnectionManager connManager;
RequestConfig defaultRequestConfig;
public ClientConfiguration() {
// Use custom message parser / writer to customize the way HTTP
// messages are parsed from and written out to the data stream.
HttpMessageParserFactory responseParserFactory = new DefaultHttpResponseParserFactory() {
@Override
public HttpMessageParser create(
SessionInputBuffer buffer, MessageConstraints constraints) {
LineParser lineParser = new BasicLineParser() {
@Override
public Header parseHeader(final CharArrayBuffer buffer) {
try {
return super.parseHeader(buffer);
} catch (ParseException ex) {
return new BasicHeader(buffer.toString(), null);
}
}
};
return new DefaultHttpResponseParser(
buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) {
@Override
protected boolean reject(final CharArrayBuffer line, int count) {
// try to ignore all garbage preceding a status line infinitely
return false;
}
};
}
};
HttpMessageWriterFactory requestWriterFactory = new DefaultHttpRequestWriterFactory();
// Use a custom connection factory to customize the process of
// initialization of outgoing HTTP connections. Beside standard connection
// configuration parameters HTTP connection factory can define message
// parser / writer routines to be employed by individual connections.
HttpConnectionFactory connFactory = new ManagedHttpClientConnectionFactory(
requestWriterFactory, responseParserFactory);
// Client HTTP connection objects when fully initialized can be bound to
// an arbitrary network socket. The process of network socket initialization,
// its connection to a remote address and binding to a local one is controlled
// by a connection socket factory.
// SSL context for secure connections can be created either based on
// system or application specific properties.
try {
SSLContext sslcontext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
// Create a registry of custom connection socket factories for supported
// protocol schemes.
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, hostnameVerifier);
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslConnectionSocketFactory)
.build();
// Create a connection manager with custom configuration.
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry, connFactory);
// Create socket configuration
SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.build();
// Configure the connection manager to use socket configuration either
// by default or for a specific host.
connManager.setDefaultSocketConfig(socketConfig);
// Validate connections after 1 sec of inactivity
connManager.setValidateAfterInactivity(1000);
// Create message constraints
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
// Configure the connection manager to use connection configuration either
connManager.setDefaultConnectionConfig(connectionConfig);
// Configure total max or per route limits for persistent connections
// that can be kept in the pool or leased by the connection manager.
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
// Create global request configuration
this.defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(20000)
.setConnectTimeout(20000)
.setConnectionRequestTimeout(20000)
.setcookieSpec(cookieSpecs.DEFAULT)
.setExpectContinueEnabled(true)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
this.httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
public JSonObject get(String url, Map paramMap) {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpget = new HttpGet(url);
httpget.setConfig(this.defaultRequestConfig);
if (!StringUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httpget.addHeader(key, paramMap.get(key).toString());
}
}
response = httpclient.execute(httpget, HttpClientContext.create());
JSonObject jsonObject = null;
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
if (httpget != null) {
try {
httpget.clone();
} catch (Exception e) {
logger.error("catch Exception:", e);
}
}
}
}
public Integer getResultCode(String url) {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpget = new HttpGet(url);
httpget.setConfig(this.defaultRequestConfig);
response = httpclient.execute(httpget, HttpClientContext.create());
return response.getStatusLine().getStatusCode();
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
if (httpget != null) {
try {
httpget.clone();
} catch (Exception e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSonObject sendGet(String url, Map paramMap) {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
List paramList = new linkedList<>();
for (String key : paramMap.keySet()) {
Object value = paramMap.get(key);
if (value != null) {
paramList.add(new BasicNamevaluePair(key, value.toString()));
}
}
uriBuilder.setParameters(paramList);
CloseableHttpClient httpclient = this.httpclient;
httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(this.defaultRequestConfig);
response = httpclient.execute(httpget, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
logger.info("http请求" + url + "结果状态码为:" + statusCode);
JSonObject jsonObject = null;
if (statusCode == 200) {
String contentType = response.getEntity().getContentType().getValue();
//影像格式
if (contentType.contains("image")) {
int imageSize = (int) response.getEntity().getContentLength();
if (imageSize > 0) {
byte imageData[] = new byte[imageSize];
response.getEntity().getContent().read(imageData);
Map tmp = new HashMap<>();
tmp.put("image", imageData);
jsonObject = JSON.parseObject(JSON.toJSONString(tmp));
}
} else {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
}
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSonObject sendPost(String url, String body) {
HttpPost httppost = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httppost = new HttpPost(url);
httppost.setConfig(this.defaultRequestConfig);
httppost.addHeader("Content-Type", "application/json");
httppost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
response = httpclient.execute(httppost, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
logger.info("http请求" + url + "结果状态码为:" + statusCode);
JSonObject jsonObject;
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
logger.error("http请求" + url + "结果状态码为:", statusCode);
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSonObject sendPost(String url, Map paramMap, String body) {
HttpPost httppost = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httppost = new HttpPost(url);
httppost.setConfig(this.defaultRequestConfig);
httppost.addHeader("Content-Type", "application/json");
if (!CollectionUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httppost.addHeader(key, paramMap.get(key).toString());
}
}
httppost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
response = httpclient.execute(httppost, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
JSonObject jsonObject;
logger.info("http请求" + url + "结果状态码为:" + statusCode);
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSonObject sendPut(String url, Map paramMap, String body) {
HttpPut httpPut = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpPut = new HttpPut(url);
httpPut.setConfig(this.defaultRequestConfig);
httpPut.addHeader("Content-Type", "application/json");
if (!CollectionUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httpPut.addHeader(key, paramMap.get(key).toString());
}
}
if (!StringUtils.isEmpty(body)) {
httpPut.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
}
response = httpclient.execute(httpPut, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
JSonObject jsonObject;
logger.info("http请求" + url + "结果状态码为:" + statusCode);
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSonObject sendDelete(String url, Map paramMap) {
HttpDelete httpDelete = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpDelete = new HttpDelete(url);
httpDelete.setConfig(this.defaultRequestConfig);
httpDelete.addHeader("Content-Type", "application/json");
if (!CollectionUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httpDelete.addHeader(key, paramMap.get(key).toString());
}
}
response = httpclient.execute(httpDelete, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
JSonObject jsonObject;
logger.info("http请求" + url + "结果状态码为:" + statusCode);
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
}
批量重新传输的ServiceImpl实现
@Override
public ServiceResult retransmissionByPlanIdBatch(String[] planIdArray) {
ServiceResult result = new ServiceResult(false);
if(planIdArray.length==0 || null==planIdArray){
result.setMessage("参数缺失");
return result;
}
for(int i=0;i