| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069 |
- package com.uas.eis.utils;
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.security.KeyManagementException;
- import java.security.NoSuchAlgorithmException;
- import java.security.cert.CertificateException;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.Map.Entry;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.TrustManager;
- import javax.net.ssl.X509TrustManager;
- import com.uas.eis.config.VwmsConfig;
- import org.apache.http.Consts;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpDelete;
- import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.methods.HttpPut;
- import org.apache.http.client.methods.HttpRequestBase;
- import org.apache.http.config.Registry;
- import org.apache.http.config.RegistryBuilder;
- import org.apache.http.conn.socket.ConnectionSocketFactory;
- import org.apache.http.conn.socket.PlainConnectionSocketFactory;
- import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.entity.mime.content.FileBody;
- import org.apache.http.entity.mime.content.InputStreamBody;
- import org.apache.http.entity.mime.content.StringBody;
- 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.protocol.HTTP;
- import org.springframework.http.HttpStatus;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.multipart.MultipartFile;
- /**
- * HTTP工具类,封装http请求
- *
- * @author suntg
- * @date 2015年3月5日14:20:40
- */
- @SuppressWarnings("deprecation")
- public class HttpUtil {
-
- /**
- * 绕过验证
- *
- * @return
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- */
- public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext sc = SSLContext.getInstance("TLSv1.2");
-
- // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
- X509TrustManager trustManager = new X509TrustManager() {
- @Override
- public void checkClientTrusted(
- java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
- String paramString) throws CertificateException {
- }
-
- @Override
- public void checkServerTrusted(
- java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
- String paramString) throws CertificateException {
- }
-
- @Override
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- };
-
- sc.init(null, new TrustManager[] { trustManager }, null);
- return sc;
- }
- /**
- * 发送GET请求
- *
- * @param url
- * @param params
- * @return
- * @throws Exception
- */
- public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
- return sendGetRequest(url, header, params, false, null);
- }
- /**
- * 发送GET请求
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
- return sendRequest(RequestMethod.GET, url, header, params, sign, signKey);
- }
- /**
- * 发送GET请求
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
- return sendRequest(RequestMethod.GET, url, header, params, sign, null);
- }
- /**
- * 发送POST请求
- *
- * @param url
- * @param params
- * @return
- * @throws Exception
- */
- public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
- return sendPostRequest(url, header, params, false, null);
- }
- /**
- * 发送POST请求
- *
- * @param url
- * @param params
- * @return
- * @throws Exception
- */
- public static Response sendPostRequest(String url, List<?> datas) throws Exception {
- return sendPostRequest(url, datas, false, null);
- }
- /**
- * 发送POST请求
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
- return sendRequest(RequestMethod.POST, url, header, params, sign, signKey);
- }
- /**
- * 发送POST请求
- *
- * @param url
- * @param datas
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPostRequest(String url, List<?> datas, boolean sign, String signKey) throws Exception {
- return sendRequest(RequestMethod.POST, url, datas, sign, signKey);
- }
- /**
- * 发送POST请求
- *
- * <pre>
- * 使用默认密钥
- * </pre>
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
- return sendRequest(RequestMethod.POST, url, header, params, sign, null);
- }
- public static Response sendPostRequest(String url, HashMap<String, String> header, String body) throws Exception {
- return sendRequest(RequestMethod.POST, url, header, body, false, null);
- }
- /**
- * 发送POST请求
- *
- * <pre>
- * 使用默认密钥
- * </pre>
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPostRequest(String url, List<?> datas, boolean sign) throws Exception {
- return sendRequest(RequestMethod.POST, url, datas, sign, null);
- }
- /**
- * 发送post请求
- *
- * @param postUrl
- * @param formData
- * @return
- * @throws Exception
- */
- public static Response doPost(String postUrl, String formData, boolean sign, String signKey) throws Exception {
- CloseableHttpClient httpClient = HttpClients.createDefault();
- postUrl = getUrl(postUrl, sign, signKey);
- HttpPost post = new HttpPost(postUrl);
- StringEntity postingString = new StringEntity(formData, HTTP.UTF_8);
- post.setEntity(postingString);
- post.setHeader("Content-type", "application/json");
- CloseableHttpResponse response = httpClient.execute(post);
- return Response.getResponse(response);
- }
- public static Response doPost(String postUrl, String formData, boolean sign, String signKey, int timeout) throws Exception {
- URL url = new URL(postUrl);
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- try {
- urlConn.setDoOutput(true);
- urlConn.setDoInput(true);
- urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
- urlConn.setUseCaches(false);
- urlConn.setInstanceFollowRedirects(true);
- urlConn.setRequestMethod("POST");
- urlConn.setConnectTimeout(timeout);
- urlConn.setReadTimeout(timeout);
- if (null != formData) {
- OutputStreamWriter osw = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
- osw.write(formData);
- osw.flush();
- osw.close();
- }
- return new Response(urlConn.getResponseCode() == 200, streamToString(urlConn.getInputStream()));
- } catch (Exception e) {
- return new Response(false, e.getMessage());
- } finally {
- if (urlConn != null) {
- urlConn.disconnect();
- }
- }
- }
-
- public static String streamToString(InputStream in) throws Exception {
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- StringBuilder buf = new StringBuilder();
- try {
- char[] chars = new char[2048];
- for (;;) {
- int len = reader.read(chars, 0, chars.length);
- if (len < 0) {
- break;
- }
- buf.append(chars, 0, len);
- }
- } catch (Exception ex) {
- throw new Exception("read string from reader error", ex);
- }
- return buf.toString();
- }
- /**
- * 封装加密
- *
- * @param postUrl
- * @param sign
- * @param signKey
- * @return
- */
- private static String getUrl(String url, boolean sign, String signKey) {
- StringBuilder buf = new StringBuilder(url);
- if (sign) {
- // 加时间戳,保持相同请求每次签名均不一样
- buf.append("&_timestamp=").append(System.currentTimeMillis());
- String message = buf.toString();
- // 对请求串进行签名
- buf.append("&_signature=").append(HmacUtils.encode(message, signKey));
- } else
- buf.deleteCharAt(buf.length() - 1);
- return buf.toString();
- }
- /**
- * 发送PUT请求
- *
- * <pre>
- * 使用默认密钥
- * </pre>
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPutRequest(String url, List<?> datas, boolean sign) throws Exception {
- return sendRequest(RequestMethod.PUT, url, datas, sign, null);
- }
- /**
- * 发送PUT请求
- *
- * <pre>
- * 使用默认密钥
- * </pre>
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPutRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
- return sendRequest(RequestMethod.PUT, url, header, params, sign, null);
- }
- /**
- * 发送PUT请求
- *
- * @param url
- * @param datas
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendPutRequest(String url, List<?> datas, boolean sign, String signKey) throws Exception {
- return sendRequest(RequestMethod.PUT, url, datas, sign, signKey);
- }
- /**
- * 发送PUT请求
- *
- * @param url
- * @param params
- * @return
- * @throws Exception
- */
- public static Response sendPutRequest(String url, List<?> datas) throws Exception {
- return sendPutRequest(url, datas, false, null);
- }
- /**
- * 发送DELETE请求
- *
- * @param url
- * @param params
- *
- * @return
- * @throws Exception
- */
- public static Response sendDeleteRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
- return sendDeleteRequest(url, header, params, false, null);
- }
- /**
- * 发送DELETE请求
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendDeleteRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
- return sendRequest(RequestMethod.DELETE, url, header, params, sign, signKey);
- }
- /**
- * 发送DELETE请求
- *
- * @param url
- * @param params
- * @param sign
- * 是否发送签名
- * @return
- * @throws Exception
- */
- public static Response sendDeleteRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
- return sendRequest(RequestMethod.DELETE, url, header, params, sign, null);
- }
- /**
- * 发起http请求
- *
- * @param method
- * 请求方法GET、POST、PUT、DELETE
- * @param url
- * 请求链接
- * @param params
- * 参数
- *
- * @param sign
- * 是否签名
- * @return
- * @throws Exception
- */
- public static Response sendRequest(RequestMethod method, String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey)
- throws Exception {
-
- switch (method) {
- case GET: {
- HttpRequestBase request = new HttpGet(getRequestUrl(url, params, sign, signKey));
- for (Map.Entry<String, String> entry : header.entrySet()) {
- request.setHeader(entry.getKey(), entry.getValue());
- }
- return sendHttpUriRequest(request);
- }
- case POST: {
- HttpPost request = new HttpPost(getRequestUrl(url, sign, signKey));
- for (Map.Entry<String, String> entry : header.entrySet()) {
- request.setHeader(entry.getKey(), entry.getValue());
- }
- return sendHttpEntityEnclosingRequest(request, params);
- }
- case PUT: {
- HttpPut request = new HttpPut(getRequestUrl(url, sign, signKey));
- for (Map.Entry<String, String> entry : header.entrySet()) {
- request.setHeader(entry.getKey(), entry.getValue());
- }
- return sendHttpEntityEnclosingRequest(request, params);
- }
- case DELETE: {
- HttpDelete request = new HttpDelete(getRequestUrl(url, params, sign, signKey));
- for (Map.Entry<String, String> entry : header.entrySet()) {
- request.setHeader(entry.getKey(), entry.getValue());
- }
- return sendHttpUriRequest(request);
- }
- default: {
- HttpGet request = new HttpGet(getRequestUrl(url, params, sign, signKey));
- for (Map.Entry<String, String> entry : header.entrySet()) {
- request.setHeader(entry.getKey(), entry.getValue());
- }
- return sendHttpUriRequest(request);
- }
- }
- }
- public static Response sendRequest(RequestMethod method, String url, HashMap<String, String> header, String body, boolean sign, String signKey)
- throws Exception {
- HttpPost request = new HttpPost(getRequestUrl(url, sign, signKey));
- for (Map.Entry<String, String> entry : header.entrySet()) {
- request.setHeader(entry.getKey(), entry.getValue());
- }
- //采用绕过验证的方式处理https请求
- SSLContext sslcontext = createIgnoreVerifySSL();
- // 设置协议http和https对应的处理socket链接工厂的对象
- Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.INSTANCE)
- .register("https", new SSLConnectionSocketFactory(sslcontext))
- .build();
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- HttpClients.custom().setConnectionManager(connManager);
- //创建自定义的httpclient对象
- CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
- CloseableHttpResponse response = null;
- try {
- request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
- request.setEntity(new StringEntity(body,"UTF-8"));
- response = httpClient.execute(request);
- return Response.getResponse(response);
- } finally {
- request.releaseConnection();
- try {
- httpClient.close();
- } catch (IOException e) {
- }
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- }
- }
- }
- }
- /**
- * 发起http请求
- *
- * @param method
- * 请求方法POST、PUT
- * @param url
- * 请求链接
- * @param datas
- * 参数
- * @param sign
- * 是否签名
- * @return
- * @throws Exception
- */
- public static Response sendRequest(RequestMethod method, String url, List<?> datas, boolean sign, String signKey) throws Exception {
- switch (method) {
- case POST:
- return sendHttpEntityEnclosingRequest(new HttpPost(getRequestUrl(url, sign, signKey)), datas);
- case PUT:
- return sendHttpEntityEnclosingRequest(new HttpPut(getRequestUrl(url, sign, signKey)), datas);
- default:
- return sendHttpEntityEnclosingRequest(new HttpPost(getRequestUrl(url, sign, signKey)), datas);
- }
- }
- /**
- * 发起GET、DELETE请求
- *
- * @param request
- * @return
- * @throws Exception
- */
- private static Response sendHttpUriRequest(HttpRequestBase request) throws Exception {
- //采用绕过验证的方式处理https请求
- SSLContext sslcontext = createIgnoreVerifySSL();
-
- // 设置协议http和https对应的处理socket链接工厂的对象
- Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.INSTANCE)
- .register("https", new SSLConnectionSocketFactory(sslcontext))
- .build();
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- HttpClients.custom().setConnectionManager(connManager);
-
- //创建自定义的httpclient对象
- CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
- //CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- try {
- response = httpClient.execute(request);
- return Response.getResponse(response);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- }
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- }
- }
- }
- }
- /**
- * 发起POST、PUT请求
- *
- * @param request
- * @param params
- * @return
- * @throws Exception
- */
- private static Response sendHttpEntityEnclosingRequest(HttpEntityEnclosingRequestBase request, Map<String, String> params)
- throws Exception {
- //采用绕过验证的方式处理https请求
- SSLContext sslcontext = createIgnoreVerifySSL();
-
- // 设置协议http和https对应的处理socket链接工厂的对象
- Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.INSTANCE)
- .register("https", new SSLConnectionSocketFactory(sslcontext))
- .build();
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- HttpClients.custom().setConnectionManager(connManager);
-
- //创建自定义的httpclient对象
- CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
- //CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- try {
- List<NameValuePair> nvps = new ArrayList<NameValuePair>();
- if (params != null && !params.isEmpty()) {
- Set<Entry<String, String>> entrys = params.entrySet();
- for (Map.Entry<String, String> entry : entrys) {
- nvps.add(new BasicNameValuePair(entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8")));
- }
- }
- request.setEntity(new UrlEncodedFormEntity(nvps));
- response = httpClient.execute(request);
- return Response.getResponse(response);
- } finally {
- request.releaseConnection();
- try {
- httpClient.close();
- } catch (IOException e) {
- }
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- }
- }
- }
- }
- /**
- * 发起POST、PUT请求
- *
- * @param request
- * @param datas
- * @return
- * @throws Exception
- */
- private static Response sendHttpEntityEnclosingRequest(HttpEntityEnclosingRequestBase request, List<?> datas) throws Exception {
- //采用绕过验证的方式处理https请求
- SSLContext sslcontext = createIgnoreVerifySSL();
-
- // 设置协议http和https对应的处理socket链接工厂的对象
- Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.INSTANCE)
- .register("https", new SSLConnectionSocketFactory(sslcontext))
- .build();
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- HttpClients.custom().setConnectionManager(connManager);
-
- //创建自定义的httpclient对象
- CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
- //CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- try {
- if (datas != null && !datas.isEmpty()) {
- request.setEntity(new StringEntity(FlexJsonUtil.toJsonArrayDeep(datas), ContentType.create("text/plain", Consts.UTF_8)));
- }
- response = httpClient.execute(request);
- return Response.getResponse(response);
- } finally {
- request.releaseConnection();
- try {
- httpClient.close();
- } catch (IOException e) {
- }
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- }
- }
- }
- }
- /**
- * 将请求参数添加到链接中
- *
- * @param url
- * @param params
- * @param sign
- * 是否签名
- * @return
- * @throws UnsupportedEncodingException
- */
- public static String getRequestUrl(String url, Map<String, String> params, boolean sign) throws UnsupportedEncodingException {
- StringBuilder buf = new StringBuilder(url);
- if (url.indexOf("?") == -1)
- buf.append("?");
- else if (!url.endsWith("&"))
- buf.append("&");
- // 如果是GET请求,则请求参数在URL中
- if (params != null && !params.isEmpty()) {
- Set<Entry<String, String>> entrys = params.entrySet();
- for (Map.Entry<String, String> entry : entrys) {
- buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
- }
- }
- if (sign) {
- // 加时间戳,保持相同请求每次签名均不一样
- buf.append("_timestamp=").append(System.currentTimeMillis());
- String message = buf.toString();
- // 对请求串进行签名
- buf.append("&_signature=").append(HmacUtils.encode(message));
- } else
- buf.deleteCharAt(buf.length() - 1);
- return buf.toString();
- }
- /**
- * 将请求参数添加到链接中
- *
- * @param url
- * @param params
- * @param sign
- * 是否签名
- * @param signKey
- * 签名密钥
- * @return
- * @throws UnsupportedEncodingException
- */
- public static String getRequestUrl(String url, Map<String, String> params, boolean sign, String signKey)
- throws UnsupportedEncodingException {
- if (sign && signKey == null)
- return getRequestUrl(url, params, sign);
- StringBuilder buf = new StringBuilder(url);
- if (url.indexOf("?") == -1)
- buf.append("?");
- else if (!url.endsWith("&"))
- buf.append("&");
- // 如果是GET请求,则请求参数在URL中
- if (params != null && !params.isEmpty()) {
- Set<Entry<String, String>> entrys = params.entrySet();
- for (Map.Entry<String, String> entry : entrys) {
- buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
- }
- }
- if (sign) {
- // 加时间戳,保持相同请求每次签名均不一样
- buf.append("_timestamp=").append(System.currentTimeMillis());
- String message = buf.toString();
- // 对请求串进行签名
- buf.append("&_signature=").append(HmacUtils.encode(message, signKey));
- } else
- buf.deleteCharAt(buf.length() - 1);
- return buf.toString();
- }
- /**
- * 将签名信息添加到链接中
- *
- * @param url
- * @param sign
- * 是否签名
- * @return
- * @throws UnsupportedEncodingException
- */
- private static String getRequestUrl(String url, boolean sign, String signKey) throws UnsupportedEncodingException {
- return getRequestUrl(url, null, sign, signKey);
- }
- /**
- * 将输入流转为字节数组
- *
- * @param inStream
- * @return
- * @throws Exception
- */
- public static byte[] read2Byte(InputStream inStream) throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- /**
- * 将输入流转为字符串
- *
- * @param inStream
- * @return
- * @throws Exception
- */
- public static String read2String(InputStream inStream) throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- try {
- outSteam.close();
- inStream.close();
- } catch (Exception e) {
- }
- return new String(outSteam.toByteArray(), "UTF-8");
- }
- /**
- * 发送xml数据
- *
- * @param path
- * 请求地址
- * @param xml
- * xml数据
- * @param encoding
- * 编码
- * @return
- * @throws Exception
- */
- public static byte[] postXml(String path, String xml, String encoding) throws Exception {
- byte[] data = xml.getBytes(encoding);
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- conn.setConnectTimeout(5 * 1000);
- OutputStream outStream = conn.getOutputStream();
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if (conn.getResponseCode() == HttpStatus.OK.value()) {
- return read2Byte(conn.getInputStream());
- }
- return null;
- }
- /**
- * http上传文件
- *
- * @param postUrl
- * 请求地址
- * @param filePath
- * 附件路径
- * @param params
- * 参数
- * @return
- * @throws Exception
- * @throws IOException
- * @throws IllegalStateException
- */
- public static Response upload(String postUrl, String filePath, Map<String, String> params, boolean sign, String signKey)
- throws IllegalStateException, IOException, Exception {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(getRequestUrl(postUrl, sign, signKey));
- FileBody fileBody = new FileBody(new File(filePath));
- MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.addPart("file", fileBody);
- if (params != null) {
- for (String paramKey : params.keySet()) {
- StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
- builder.addPart(paramKey, body);
- }
- }
- HttpEntity reqEntity = builder.build();
- httpPost.setEntity(reqEntity);
- response = httpClient.execute(httpPost);
- } finally {
- try {
- if (response != null) {
- response.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return Response.getResponse(response);
- }
- /**
- * http上传文件
- *
- * @param postUrl
- * 请求地址
- * @param file
- * 附件
- * @param params
- * 参数
- * @return
- * @throws Exception
- * @throws IOException
- * @throws IllegalStateException
- */
- public static Response upload(String postUrl, MultipartFile file, Map<String, String> params, boolean sign, String signKey)
- throws IllegalStateException, IOException, Exception {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(getRequestUrl(postUrl, sign, signKey));
- InputStreamBody sbody = new InputStreamBody(file.getInputStream(), file.getOriginalFilename());
- MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.addPart("file", sbody);
- if (params != null) {
- for (String paramKey : params.keySet()) {
- StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
- builder.addPart(paramKey, body);
- }
- }
- HttpEntity reqEntity = builder.build();
- httpPost.setEntity(reqEntity);
- response = httpClient.execute(httpPost);
- } finally {
- try {
- if (response != null) {
- response.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return Response.getResponse(response);
- }
- /**
- * 下载
- *
- * @param postUrl
- * @return
- * @throws ClientProtocolException
- * @throws IOException
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- */
- public static InputStream download(String postUrl) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException {
- //采用绕过验证的方式处理https请求
- SSLContext sslcontext = createIgnoreVerifySSL();
-
- // 设置协议http和https对应的处理socket链接工厂的对象
- Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.INSTANCE)
- .register("https", new SSLConnectionSocketFactory(sslcontext))
- .build();
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- HttpClients.custom().setConnectionManager(connManager);
-
- //创建自定义的httpclient对象
- CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
- //CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet(postUrl);
- CloseableHttpResponse response = httpClient.execute(httpGet);
- return response.getEntity().getContent();
- }
- public static Response doPostToVWMS(String method,String formData, VwmsConfig vwmsConfig) throws Exception {
- CloseableHttpClient httpClient = HttpClients.createDefault();
- String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
- //"{secretkey}app_key{app_key}customerId{customerId}formatjsonmethod{openapi_name}sign_methodmd5timestamp2015-04-26 00:00:07v2.0{body}{secretkey}";
- String signMsg= String.format("%sapp_key%scustomerId%sformatjsonmethod%ssign_methodmd5timestamp%sv2.0%s%s",
- vwmsConfig.getAppSecret(),vwmsConfig.getAppKey(), vwmsConfig.getCustomerId(),method,timestamp,formData,vwmsConfig.getAppSecret() );
- //http://{openapiUrl}?method=openapi.singleitem.synchronize×tamp=2015-04-26%2000:00:07&format=json&app_key={app_key}&v=2.0&sign=D06D88CB34B2EC0E5C9BAB396C9542B6&sign_method=md5&customerId={customerId}
- StringBuilder postUrl = new StringBuilder(vwmsConfig.getApiUrl());
- postUrl.append("?method=").append(method)
- .append("×tamp=").append(System.currentTimeMillis()).append("&format=json").append("&app_key=").append(vwmsConfig.getAppKey())
- .append("&v=2.0")
- .append("&_signature=").append(HmacUtils.encode(signMsg, vwmsConfig.getAppSecret())) // 对请求串进行签名
- .append("&sign_method=md5").append("&customerId=").append(vwmsConfig.getCustomerId());
- // System.out.println("postUrl:"+postUrl.toString());
- // System.out.println("postingString:"+formData.toString());
- // postUrl = new StringBuilder();
- HttpPost post = new HttpPost(postUrl.toString());
- StringEntity postingString = new StringEntity(formData, HTTP.UTF_8);
- post.setEntity(postingString);
- post.setHeader("Content-type", "application/json");
- CloseableHttpResponse response = httpClient.execute(post);
- return Response.getResponse(response);
- }
- public static byte[] postXmlToVWMS(String method, String xml, String encoding,VwmsConfig vwmsConfig) throws Exception {
- byte[] data = xml.getBytes(encoding);
- String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
- //"{secretkey}app_key{app_key}customerId{customerId}formatjsonmethod{openapi_name}sign_methodmd5timestamp2015-04-26 00:00:07v2.0{body}{secretkey}";
- String signMsg= String.format("%sapp_key%scustomerId%sformatjsonmethod%ssign_methodmd5timestamp%sv2.0%s%s",
- vwmsConfig.getAppSecret(),vwmsConfig.getAppKey(), vwmsConfig.getCustomerId(),method,timestamp,xml,vwmsConfig.getAppSecret() );
- StringBuilder postUrl = new StringBuilder(vwmsConfig.getApiUrl());
- postUrl.append("?method=").append(method)
- .append("×tamp=").append(System.currentTimeMillis()).append("&format=xml").append("&app_key=").append(vwmsConfig.getAppKey())
- .append("&v=2.0")
- .append("&_signature=").append(HmacUtils.encode(signMsg, vwmsConfig.getAppSecret())) // 对请求串进行签名
- .append("&sign_method=md5").append("&customerId=").append(vwmsConfig.getCustomerId());
- URL url = new URL(postUrl.toString());
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- conn.setConnectTimeout(5 * 1000);
- OutputStream outStream = conn.getOutputStream();
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if (conn.getResponseCode() == HttpStatus.OK.value()||conn.getResponseCode() == HttpStatus.CREATED.value()) {
- return read2Byte(conn.getInputStream());
- }
- return null;
- }
- public static class Response {
- private int statusCode;
- private String responseText;
- public int getStatusCode() {
- return statusCode;
- }
- public void setStatusCode(int statusCode) {
- this.statusCode = statusCode;
- }
- public String getResponseText() {
- return responseText;
- }
- public void setResponseText(String responseText) {
- this.responseText = responseText;
- }
- public Response() {
- }
- public Response(boolean success, String content) {
- super();
- this.statusCode = success ? 200 : 404;
- this.responseText = content;
- }
-
- public Response(HttpResponse response) throws IllegalStateException, IOException, Exception {
- this.statusCode = response.getStatusLine().getStatusCode();
- this.responseText = HttpUtil.read2String(response.getEntity().getContent());
- }
- public static Response getResponse(HttpResponse response) throws IllegalStateException, IOException, Exception {
- if (response != null)
- return new Response(response);
- return null;
- }
- }
- }
|