Commit 1afa87f7 by 徐高华

出口ip

parent c506be8c
package com.gic.qywx.self;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
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.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSON;
public class HttpClient {
private static Logger logger = LogManager.getLogger(HttpClient.class);
private static org.apache.http.client.HttpClient mHttpClient;
private static CookieStore cookieStore = new BasicCookieStore();
public static final int DEFAULT_MAX_CONNECTIONS = 1000;
public static final int DEFAULT_MAX_ROUTE_CONNECTIONS = 100;
public static final int DEFAULT_SOCKET_TIMEOUT = 20 * 1000;
public static final int DEFAULT_CONNECT_TIMEOUT = 30 * 1000;
public static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
private static Map<Long, org.apache.http.client.HttpClient> clientByTimeoutMap = new HashMap<>();
public static org.apache.http.client.HttpClient createHttpClient(int socketTimeOut) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ConnManagerParams.setTimeout(params, DEFAULT_SOCKET_TIMEOUT);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS));
ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONNECTIONS);
HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, socketTimeOut);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSoReuseaddr(params, true);
HttpConnectionParams.setSoKeepalive(params, true);
HttpConnectionParams.setSocketBufferSize(params, DEFAULT_SOCKET_BUFFER_SIZE);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
DefaultHttpClient httpClient = new DefaultHttpClient(conMgr, params);
return httpClient;
}
protected static org.apache.http.client.HttpClient getHttpClient() {
/**
* old version
* **/
if (null == mHttpClient) {
synchronized (HttpClient.class) {
if (null == mHttpClient) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ConnManagerParams.setTimeout(params, DEFAULT_SOCKET_TIMEOUT);
ConnManagerParams.setMaxConnectionsPerRoute(params,
new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS));
ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONNECTIONS);
HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, DEFAULT_SOCKET_TIMEOUT);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSoReuseaddr(params, true);
HttpConnectionParams.setSoKeepalive(params, true);
HttpConnectionParams.setSocketBufferSize(params, DEFAULT_SOCKET_BUFFER_SIZE);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
mHttpClient = new DefaultHttpClient(conMgr, params);
}
}
}
// org.apache.http.client.CookieStore cookieStore = ((DefaultHttpClient) mHttpClient).getCookieStore();
// cookieStore.clear();
return mHttpClient;
}
public static Map<String, Object> getWinxinResByJson(String url, String jsonStr) {
return getWinxinResByJson(url, jsonStr, null);
}
public static Map<String, Object> getWinxinResByJson(String url, String jsonStr, Map<String, String> header) {
long begin = new Date().getTime();
String resInfo = null;
Map<String, Object> weixinMap = new HashMap<String, Object>();
org.apache.http.client.HttpClient client = getHttpClient();
HttpPost post = new HttpPost(url);
StringBuilder builder = new StringBuilder();
if (null != header) {
for (Entry<String, String> entry : header.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
}
try {
if (null != jsonStr) {
post.setEntity(new StringEntity(jsonStr, "utf-8"));
}
HttpResponse response = client.execute(post);
resInfo = EntityUtils.toString(response.getEntity(), "utf-8");
weixinMap = JSON.parseObject(resInfo, Map.class);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + resInfo);
}
return weixinMap;
}
public static Object getWinxinResByJsonToObj(String url, String jsonStr, Class clazz) {
return getWinxinResByJsonToObj(url, jsonStr, clazz, "POST");
}
public static Object getWinxinResByJsonToObj(String url, String jsonStr, Class clazz, String method) {
long begin = new Date().getTime();
String resInfo = null;
Object obj = null;
org.apache.http.client.HttpClient client = getHttpClient();
HttpResponse response = null;
try {
if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
if (null != jsonStr) {
post.setEntity(new StringEntity(jsonStr, "utf-8"));
}
response = client.execute(post);
}
if ("GET".equals(method)) {
HttpGet get = new HttpGet(url);
response = client.execute(get);
}
resInfo = EntityUtils.toString(response.getEntity(), "utf-8");
obj = JSON.parseObject(resInfo, clazz);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + resInfo);
}
return obj;
}
public static Map<String, Object> getWinxinResByFile(String url, Map<String, ContentBody> map) {
long begin = new Date().getTime();
String entityStr = null;
MultipartEntity entity = new MultipartEntity();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
entity.addPart(keyString, map.get(keyString));
}
Map<String, Object> obj = null;
org.apache.http.client.HttpClient client = getHttpClient();
HttpPost post = new HttpPost(url);
StringBuilder builder = new StringBuilder();
try {
post.setEntity(entity);
HttpResponse response = client.execute(post);
entityStr = EntityUtils.toString(response.getEntity(), "utf-8");
obj = JSON.parseObject(entityStr, Map.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new HashMap<String, Object>();
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + map + " res:" + entityStr);
}
return obj;
}
public static Map<String, Object> getWinxinRes(String url, Map<String, String> map) {
Object obj = getWinxinRes(url, map, Map.class, "POST");
if (null != obj)
return (Map<String, Object>) obj;
return null;
}
public static Map<String, Object> getWinxinRes(String url, Map<String, String> map, String method) {
Object obj = getWinxinRes(url, map, Map.class, method);
if (null != obj)
return (Map<String, Object>) obj;
return null;
}
public static Object getWinxinRes(String url, Map<String, String> map, Class clazz) {
return getWinxinRes(url, map, clazz, "POST");
}
public static Object getWinxinRes(String url, Map<String, String> map, Class clazz, String method) {
long begin = System.currentTimeMillis();
String entityStr = null;
Object obj = null;
org.apache.http.client.HttpClient client = getHttpClient();
HttpResponse response = null;
try {
if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
nvps.add(new BasicNameValuePair(keyString, map.get(keyString)));
}
post.setEntity((HttpEntity) new UrlEncodedFormEntity(nvps, "UTF-8"));
response = client.execute(post);
}
if ("GET".equals(method)) {
if (map != null) {
if (map.size() > 0) {
if (url.indexOf("?") > 0)
url = url + "&";
else
url = url + "?";
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
url = url + keyString + "=" + map.get(keyString) + "&";
}
if (map.size() > 0)
url = url.substring(0, url.length() - 1);
}
HttpGet get = new HttpGet(url);
response = client.execute(get);
}
entityStr = EntityUtils.toString(response.getEntity(), "utf-8");
obj = JSON.parseObject(entityStr, clazz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
long end = System.currentTimeMillis();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + map + " res:" + entityStr);
}
return obj;
}
public static Map<String, Object> getWinxinResToStream(String url) {
return getWinxinResToStream(url, "POST");
}
public static Map<String, Object> getWinxinResToStream(String url, String method) {
Map<String, Object> res = new HashMap<String, Object>();
byte[] content = null;
List<byte[]> contentList = new ArrayList<byte[]>();
org.apache.http.client.HttpClient client = getHttpClient();
HttpResponse response = null;
InputStream is = null;
String fileName = null;
try {
if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
response = client.execute(post);
}
if ("GET".equals(method)) {
HttpGet get = new HttpGet(url);
response = client.execute(get);
}
for (Header header : response.getAllHeaders()) {
String info = header.getValue();
if (info.contains("filename="))
fileName = URLDecoder.decode(info.substring(info.indexOf("filename=") + 9), "UTF-8");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
byte[] arr = new byte[1024];
int len = 0;
int sumlen = 0;
while ((len = is.read(arr)) != -1) {
sumlen = sumlen + len;
int begin = 0;
byte[] info = new byte[len];
for (byte b : arr) {
if (begin < len) {
info[begin] = b;
} else {
break;
}
begin++;
}
contentList.add(info);
}
content = new byte[sumlen];
int index = 0;
for (byte[] bt : contentList) {
for (byte b : bt) {
content[index] = b;
index++;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != is)
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
res.put("content", content);
res.put("fileName", fileName);
return res;
}
}
public static interface DecryptProcess {
public String decrypt(String secretText) throws Exception;
}
public static Map<String, Object> getHttpByPost(String url, Map<String, String> map) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
nvps.add(new BasicNameValuePair(keyString, map.get(keyString)));
}
return getHttpByPost(url, nvps);
}
public static Map<String, Object> getHttpByPost(String url, String[]... params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (params != null) {
for (String[] param : params) {
nvps.add(new BasicNameValuePair(param[0], param[1]));
}
}
return getHttpByPost(url, nvps);
}
public static String sendPostJSON(String url, String body, String charset) {
HttpPost request = new HttpPost(url);
request.addHeader("content-type", "application/json");
StringEntity params = new StringEntity(body, charset);
request.setEntity(params);
return sendHttpPost(request);
}
public static String sendPostJSON(String url, String body, Map<String, String> headers, String charset) {
HttpPost request = new HttpPost(url);
request.addHeader("content-type", "application/json");
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
StringEntity params = new StringEntity(body, charset);
request.setEntity(params);
return sendHttpPost(request);
}
private static String sendHttpPost(HttpPost httpPost) {
org.apache.http.client.HttpClient httpClient = getHttpClient();
HttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
logger.error("http 请求出错:" + e);
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
return responseContent;
}
/**
* 请求返回状态码code 和 结果 result
*/
public static Map<String, Object> getHttpByPost(String url, List<NameValuePair> nvps) {
Map<String, Object> map = new HashMap<String, Object>();
org.apache.http.client.HttpClient client = getHttpClient();
HttpPost post = new HttpPost(url);
// StringBuilder builder = new StringBuilder();
// String result = null;
// String responseStr = "";
// int responseCode = 0;
HttpResponse response = null;
try {
post.setEntity((HttpEntity) new UrlEncodedFormEntity(nvps, "UTF-8"));
response = client.execute(post);
map = doResponse(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
return map;
}
public static Map<String, Object> getHttpByGet(String url, String userName, String password) {
Map<String, Object> map = new HashMap<String, Object>();
org.apache.http.client.HttpClient client = getHttpClient();
if (userName != null && password != null) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials usernamePassword = new UsernamePasswordCredentials(userName, password);
credsProvider.setCredentials(AuthScope.ANY, usernamePassword);
((AbstractHttpClient) client).setCredentialsProvider(credsProvider);
}
HttpGet get = new HttpGet(url);
get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
HttpResponse response = null;
try {
// logger.error("url:" + url);
response = client.execute(get);
map = doResponse(response);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
return map;
}
public static Map<String, Object> getHttpByGet(String url) {
return getHttpByGet(url, null, null);
}
private static Map<String, Object> doResponse(HttpResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
String line = "";
String result = null;
String responseStr = "";
int responseCode = 0;
try {
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
StringBuilder builder = new StringBuilder();
responseCode = response.getStatusLine().getStatusCode();
switch (responseCode) {
// 请求成功
case HttpURLConnection.HTTP_OK:
while ((line = reader.readLine()) != null) {
builder.append(line);
}
responseStr = builder.toString();
result = "请求成功";
break;
case HttpURLConnection.HTTP_BAD_REQUEST:
while ((line = reader.readLine()) != null) {
builder.append(line);
}
responseStr = builder.toString();
result = "错误请求";
break;
case HttpURLConnection.HTTP_INTERNAL_ERROR:
result = "服务器端错误";
break;
case HttpURLConnection.HTTP_NOT_FOUND:
result = "未找到指定的网址";
break;
case HttpURLConnection.HTTP_BAD_GATEWAY:
result = "请求超时";
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
map.put("code", HttpURLConnection.HTTP_BAD_GATEWAY);
map.put("result", "无法连接网络,请检查网络设置");
map.put("response", "");
} finally {
map.put("code", responseCode);
map.put("result", result);
map.put("response", responseStr);
}
return map;
}
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
// String url = "http://localhost:8080/gic/storegroup_list"; // http请求所访问的地址
// String url = "http://www.baidu.com"; // http请求所访问的地址
String url = "http://123.207.187.158:8999/dubbo-monitor/monitor/test"; // http请求所访问的地址
Map<String, String> reqData = new HashMap<String, String>();
// 发送请求包
Map<String, Object> get = getHttpByGet(url);
// Map<String, Object> respData = client.getHttpByPost(url, reqData);
// String responseInfo = (String) respData.get("response");
logger.info("resp:");
System.out.println(get);
}
public static String getWinxinResinfo(String url, Map<String, String> map, String method) {
long begin = new Date().getTime();
String entityStr = "";
org.apache.http.client.HttpClient client = getHttpClient();
HttpResponse response = null;
try {
if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
nvps.add(new BasicNameValuePair(keyString, map.get(keyString)));
}
post.setEntity((HttpEntity) new UrlEncodedFormEntity(nvps, "UTF-8"));
response = client.execute(post);
}
if ("GET".equals(method)) {
if (map != null) {
if (map.size() > 0) {
if (url.indexOf("?") > 0)
url = url + "&";
else
url = url + "?";
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
url = url + keyString + "=" + map.get(keyString) + "&";
}
if (map.size() > 0)
url = url.substring(0, url.length() - 1);
}
HttpGet get = new HttpGet(url);
response = client.execute(get);
}
entityStr = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + map + " res:" + entityStr);
}
return entityStr;
}
/**
* 请求
*
* @Title: httpRequest
* @Description: TODO
* @Param @param requestUrl
* @Param @param requestMethod
* @Param @param outputStr
* @Param @return
* @Return JSONObject
* @Throws
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object getWinxinResByObj(String url, String jsonStr, String method) {
long begin = new Date().getTime();
Object obj = null;
org.apache.http.client.HttpClient client = getHttpClient();
HttpResponse response = null;
try {
if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
if (null != jsonStr) {
post.setEntity(new StringEntity(jsonStr, "utf-8"));
}
response = client.execute(post);
}
if ("GET".equals(method)) {
HttpGet get = new HttpGet(url);
response = client.execute(get);
}
obj = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + obj);
}
return obj;
}
}
package com.gic.qywx.self;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
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.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSON;
public class HttpClient {
private static Logger logger = LogManager.getLogger(HttpClient.class);
private static org.apache.http.client.HttpClient mHttpClient;
public static final int DEFAULT_MAX_CONNECTIONS = 1000;
public static final int DEFAULT_MAX_ROUTE_CONNECTIONS = 100;
public static final int DEFAULT_SOCKET_TIMEOUT = 20 * 1000;
public static final int DEFAULT_CONNECT_TIMEOUT = 30 * 1000;
public static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
protected static org.apache.http.client.HttpClient getHttpClient() {
/**
* old version
* **/
if (null == mHttpClient) {
synchronized (HttpClient.class) {
if (null == mHttpClient) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ConnManagerParams.setTimeout(params, DEFAULT_SOCKET_TIMEOUT);
ConnManagerParams.setMaxConnectionsPerRoute(params,
new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS));
ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONNECTIONS);
HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, DEFAULT_SOCKET_TIMEOUT);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSoReuseaddr(params, true);
HttpConnectionParams.setSoKeepalive(params, true);
HttpConnectionParams.setSocketBufferSize(params, DEFAULT_SOCKET_BUFFER_SIZE);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
mHttpClient = new DefaultHttpClient(conMgr, params);
}
}
}
return mHttpClient;
}
public static Map<String, Object> getWinxinResByJson(String url, String jsonStr, byte[] b) {
return getWinxinResByJson(url, jsonStr, null,b);
}
public static Map<String, Object> getWinxinResByJson(String url, String jsonStr, Map<String, String> header , byte[] b) {
long begin = new Date().getTime();
String resInfo = null;
Map<String, Object> weixinMap = new HashMap<String, Object>();
org.apache.http.client.HttpClient client = getHttpClient();
setIp(client,b) ;
HttpPost post = new HttpPost(url);
StringBuilder builder = new StringBuilder();
if (null != header) {
for (Entry<String, String> entry : header.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
}
try {
if (null != jsonStr) {
post.setEntity(new StringEntity(jsonStr, "utf-8"));
}
HttpResponse response = client.execute(post);
resInfo = EntityUtils.toString(response.getEntity(), "utf-8");
weixinMap = JSON.parseObject(resInfo, Map.class);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + resInfo);
}
return weixinMap;
}
public static Map<String, Object> getWinxinResByFile(String url, Map<String, ContentBody> map , byte[] b) {
long begin = new Date().getTime();
String entityStr = null;
MultipartEntity entity = new MultipartEntity();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String keyString = iterator.next();
entity.addPart(keyString, map.get(keyString));
}
Map<String, Object> obj = null;
org.apache.http.client.HttpClient client = getHttpClient();
setIp(client,b) ;
HttpPost post = new HttpPost(url);
StringBuilder builder = new StringBuilder();
try {
post.setEntity(entity);
HttpResponse response = client.execute(post);
entityStr = EntityUtils.toString(response.getEntity(), "utf-8");
obj = JSON.parseObject(entityStr, Map.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new HashMap<String, Object>();
} finally {
long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + map + " res:" + entityStr);
}
return obj;
}
public static Map<String, Object> getHttpByGet(String url, String userName, String password , byte[] b) {
Map<String, Object> map = new HashMap<String, Object>();
org.apache.http.client.HttpClient client = getHttpClient();
setIp(client,b) ;
if (userName != null && password != null) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials usernamePassword = new UsernamePasswordCredentials(userName, password);
credsProvider.setCredentials(AuthScope.ANY, usernamePassword);
((AbstractHttpClient) client).setCredentialsProvider(credsProvider);
}
HttpGet get = new HttpGet(url);
get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
HttpResponse response = null;
try {
response = client.execute(get);
map = doResponse(response);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
return map;
}
public static Map<String, Object> getHttpByGet(String url , byte[] b) {
return getHttpByGet(url, null, null , b);
}
private static Map<String, Object> doResponse(HttpResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
String line = "";
String result = null;
String responseStr = "";
int responseCode = 0;
try {
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
StringBuilder builder = new StringBuilder();
responseCode = response.getStatusLine().getStatusCode();
switch (responseCode) {
// 请求成功
case HttpURLConnection.HTTP_OK:
while ((line = reader.readLine()) != null) {
builder.append(line);
}
responseStr = builder.toString();
result = "请求成功";
break;
case HttpURLConnection.HTTP_BAD_REQUEST:
while ((line = reader.readLine()) != null) {
builder.append(line);
}
responseStr = builder.toString();
result = "错误请求";
break;
case HttpURLConnection.HTTP_INTERNAL_ERROR:
result = "服务器端错误";
break;
case HttpURLConnection.HTTP_NOT_FOUND:
result = "未找到指定的网址";
break;
case HttpURLConnection.HTTP_BAD_GATEWAY:
result = "请求超时";
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
map.put("code", HttpURLConnection.HTTP_BAD_GATEWAY);
map.put("result", "无法连接网络,请检查网络设置");
map.put("response", "");
} finally {
map.put("code", responseCode);
map.put("result", result);
map.put("response", responseStr);
}
return map;
}
private static void setIp(org.apache.http.client.HttpClient client , byte[] b) {
try {
if(null != b) {
client.getParams().setParameter(ConnRouteParams.LOCAL_ADDRESS, InetAddress.getByAddress(b)) ;
}
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
package com.gic.qywx.self;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
......@@ -15,6 +12,7 @@ import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -28,41 +26,38 @@ public class QywxController {
private static final Logger logger = LoggerFactory.getLogger(QywxController.class);
@RequestMapping("self-post")
public Object selfPost(String url, String json) {
public Object selfPost(String url, String json, String ip) {
logger.info("自建post,url={},json={}", url, json);
Map<String, Object> map = HttpClient.getWinxinResByJson(url, json);
Map<String, Object> map = HttpClient.getWinxinResByJson(url, json, getIp(ip));
return map;
}
@RequestMapping("self-post-json")
public Object selfPostJson(String url, @RequestBody String json) {
public Object selfPostJson(String url, @RequestBody String json, String ip) {
logger.info("自建post json,url={},json={}", url, json);
Map<String, Object> map = HttpClient.getWinxinResByJson(url, json);
Map<String, Object> map = HttpClient.getWinxinResByJson(url, json, getIp(ip));
return map;
}
@RequestMapping("self-get")
public Object selfGet(String url) {
public Object selfGet(String url, String ip) {
logger.info("自建get,url={}", url);
Map<String, Object> map = HttpClient.getHttpByGet(url);
Map<String, Object> map = HttpClient.getHttpByGet(url, getIp(ip));
return map;
}
@RequestMapping("self-upload")
public Object selfUpload(String url, String fileUrl, String fileName) {
public Object selfUpload(String url, String fileUrl, String fileName, String ip) {
logger.info("自建upload,url={}", url);
byte[] data = CommonUtil.getFileByte(fileUrl);
Map<String, ContentBody> paramsMap = new HashMap<String, ContentBody>();
paramsMap.put("media", new ByteArrayBody(data, ContentType.DEFAULT_BINARY, fileName));
Map<String, Object> map = HttpClient.getWinxinResByFile(url, paramsMap);
Map<String, Object> map = HttpClient.getWinxinResByFile(url, paramsMap, getIp(ip));
return map;
}
@RequestMapping("self-upload-data")
public Object selfImage(String url, String fileName, HttpServletRequest request) throws IOException {
public Object selfImage(String url, String fileName, HttpServletRequest request, String ip) throws IOException {
logger.info("自建upload-data,url={}", url);
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> list = multiRequest.getMultiFileMap().get("media");
......@@ -70,8 +65,18 @@ public class QywxController {
byte[] data = mf.getBytes();
Map<String, ContentBody> paramsMap = new HashMap<String, ContentBody>();
paramsMap.put("media", new ByteArrayBody(data, ContentType.DEFAULT_BINARY, fileName));
Map<String, Object> map = HttpClient.getWinxinResByFile(url, paramsMap);
Map<String, Object> map = HttpClient.getWinxinResByFile(url, paramsMap, getIp(ip));
return map;
}
// 必须是内网ip
private byte[] getIp(String ip) {
logger.info("ip={}",ip);
if(StringUtils.isEmpty(ip)) {
return null ;
}
String[] arr = ip.split("\\.");
byte[] b = new byte[] {Integer.valueOf(arr[0]).byteValue(), Integer.valueOf(arr[1]).byteValue(),Integer.valueOf(arr[2]).byteValue(),Integer.valueOf(arr[3]).byteValue()};
return b;
}
}
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