Commit 1afa87f7 by 徐高华

出口ip

parent c506be8c
package com.gic.qywx.self; package com.gic.qywx.self;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStreamReader;
import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;
import java.io.OutputStream; import java.net.HttpURLConnection;
import java.io.UnsupportedEncodingException; import java.net.InetAddress;
import java.net.ConnectException; import java.net.UnknownHostException;
import java.net.HttpURLConnection; import java.util.ArrayList;
import java.net.URL; import java.util.Date;
import java.net.URLDecoder; import java.util.HashMap;
import java.util.ArrayList; import java.util.Iterator;
import java.util.Date; import java.util.List;
import java.util.HashMap; import java.util.Map;
import java.util.Iterator; import java.util.Map.Entry;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import java.util.Map.Entry; import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.Header; import org.apache.http.NameValuePair;
import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope;
import org.apache.http.HttpResponse; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.HttpVersion; import org.apache.http.client.ClientProtocolException;
import org.apache.http.NameValuePair; import org.apache.http.client.CredentialsProvider;
import org.apache.http.auth.AuthScope; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.CookieStore; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.client.CredentialsProvider; import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.entity.StringEntity;
import org.apache.http.conn.scheme.Scheme; import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.client.AbstractHttpClient; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.params.BasicHttpParams;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpProtocolParams;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP;
import org.apache.http.params.BasicHttpParams; import org.apache.http.util.EntityUtils;
import org.apache.http.params.HttpConnectionParams; import org.apache.logging.log4j.LogManager;
import org.apache.http.params.HttpParams; import org.apache.logging.log4j.Logger;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP; import com.alibaba.fastjson.JSON;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager; public class HttpClient {
import org.apache.logging.log4j.Logger; private static Logger logger = LogManager.getLogger(HttpClient.class);
import com.alibaba.fastjson.JSON; private static org.apache.http.client.HttpClient mHttpClient;
public static final int DEFAULT_MAX_CONNECTIONS = 1000;
public class HttpClient { public static final int DEFAULT_MAX_ROUTE_CONNECTIONS = 100;
private static Logger logger = LogManager.getLogger(HttpClient.class); public static final int DEFAULT_SOCKET_TIMEOUT = 20 * 1000;
public static final int DEFAULT_CONNECT_TIMEOUT = 30 * 1000;
private static org.apache.http.client.HttpClient mHttpClient; public static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
private static CookieStore cookieStore = new BasicCookieStore();
protected static org.apache.http.client.HttpClient getHttpClient() {
public static final int DEFAULT_MAX_CONNECTIONS = 1000; /**
public static final int DEFAULT_MAX_ROUTE_CONNECTIONS = 100; * old version
public static final int DEFAULT_SOCKET_TIMEOUT = 20 * 1000; * **/
public static final int DEFAULT_CONNECT_TIMEOUT = 30 * 1000; if (null == mHttpClient) {
public static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192; synchronized (HttpClient.class) {
if (null == mHttpClient) {
private static Map<Long, org.apache.http.client.HttpClient> clientByTimeoutMap = new HashMap<>(); HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
public static org.apache.http.client.HttpClient createHttpClient(int socketTimeOut) { HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); ConnManagerParams.setTimeout(params, DEFAULT_SOCKET_TIMEOUT);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ConnManagerParams.setMaxConnectionsPerRoute(params,
new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS));
ConnManagerParams.setTimeout(params, DEFAULT_SOCKET_TIMEOUT); ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONNECTIONS);
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.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT); HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSoTimeout(params, socketTimeOut); HttpConnectionParams.setSoReuseaddr(params, true);
HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true);
HttpConnectionParams.setSoReuseaddr(params, true); HttpConnectionParams.setSocketBufferSize(params, DEFAULT_SOCKET_BUFFER_SIZE);
HttpConnectionParams.setSoKeepalive(params, true);
HttpConnectionParams.setSocketBufferSize(params, DEFAULT_SOCKET_BUFFER_SIZE); SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
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);
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); }
DefaultHttpClient httpClient = new DefaultHttpClient(conMgr, params); }
return httpClient; }
} return mHttpClient;
}
protected static org.apache.http.client.HttpClient getHttpClient() {
/** public static Map<String, Object> getWinxinResByJson(String url, String jsonStr, byte[] b) {
* old version return getWinxinResByJson(url, jsonStr, null,b);
* **/ }
if (null == mHttpClient) {
synchronized (HttpClient.class) { public static Map<String, Object> getWinxinResByJson(String url, String jsonStr, Map<String, String> header , byte[] b) {
if (null == mHttpClient) {
HttpParams params = new BasicHttpParams(); long begin = new Date().getTime();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); String resInfo = null;
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); Map<String, Object> weixinMap = new HashMap<String, Object>();
org.apache.http.client.HttpClient client = getHttpClient();
ConnManagerParams.setTimeout(params, DEFAULT_SOCKET_TIMEOUT); setIp(client,b) ;
ConnManagerParams.setMaxConnectionsPerRoute(params, HttpPost post = new HttpPost(url);
new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS)); StringBuilder builder = new StringBuilder();
ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONNECTIONS);
if (null != header) {
HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT); for (Entry<String, String> entry : header.entrySet()) {
HttpConnectionParams.setSoTimeout(params, DEFAULT_SOCKET_TIMEOUT); post.addHeader(entry.getKey(), entry.getValue());
HttpConnectionParams.setTcpNoDelay(params, true); }
HttpConnectionParams.setSoReuseaddr(params, true); }
HttpConnectionParams.setSoKeepalive(params, true);
HttpConnectionParams.setSocketBufferSize(params, DEFAULT_SOCKET_BUFFER_SIZE); try {
SchemeRegistry schReg = new SchemeRegistry(); if (null != jsonStr) {
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); post.setEntity(new StringEntity(jsonStr, "utf-8"));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); }
HttpResponse response = client.execute(post);
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); resInfo = EntityUtils.toString(response.getEntity(), "utf-8");
mHttpClient = new DefaultHttpClient(conMgr, params);
} weixinMap = JSON.parseObject(resInfo, Map.class);
} } catch (UnsupportedEncodingException e) {
} // TODO Auto-generated catch block
// org.apache.http.client.CookieStore cookieStore = ((DefaultHttpClient) mHttpClient).getCookieStore(); e.printStackTrace();
// cookieStore.clear(); } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
return mHttpClient; e.printStackTrace();
} } catch (IOException e) {
// TODO Auto-generated catch block
public static Map<String, Object> getWinxinResByJson(String url, String jsonStr) { e.printStackTrace();
return getWinxinResByJson(url, jsonStr, null); } finally {
} long end = new Date().getTime();
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + resInfo);
public static Map<String, Object> getWinxinResByJson(String url, String jsonStr, Map<String, String> header) { }
return weixinMap;
long begin = new Date().getTime(); }
String resInfo = null;
Map<String, Object> weixinMap = new HashMap<String, Object>(); public static Map<String, Object> getWinxinResByFile(String url, Map<String, ContentBody> map , byte[] b) {
org.apache.http.client.HttpClient client = getHttpClient();
HttpPost post = new HttpPost(url); long begin = new Date().getTime();
StringBuilder builder = new StringBuilder(); String entityStr = null;
MultipartEntity entity = new MultipartEntity();
if (null != header) { Iterator<String> iterator = map.keySet().iterator();
for (Entry<String, String> entry : header.entrySet()) { while (iterator.hasNext()) {
post.addHeader(entry.getKey(), entry.getValue()); String keyString = iterator.next();
} entity.addPart(keyString, map.get(keyString));
} }
try { Map<String, Object> obj = null;
org.apache.http.client.HttpClient client = getHttpClient();
if (null != jsonStr) { setIp(client,b) ;
post.setEntity(new StringEntity(jsonStr, "utf-8")); HttpPost post = new HttpPost(url);
} StringBuilder builder = new StringBuilder();
HttpResponse response = client.execute(post);
resInfo = EntityUtils.toString(response.getEntity(), "utf-8"); try {
post.setEntity(entity);
weixinMap = JSON.parseObject(resInfo, Map.class); HttpResponse response = client.execute(post);
} catch (UnsupportedEncodingException e) { entityStr = EntityUtils.toString(response.getEntity(), "utf-8");
// TODO Auto-generated catch block
e.printStackTrace(); obj = JSON.parseObject(entityStr, Map.class);
} catch (ClientProtocolException e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { return new HashMap<String, Object>();
// TODO Auto-generated catch block } finally {
e.printStackTrace(); long end = new Date().getTime();
} finally { logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + map + " res:" + entityStr);
long end = new Date().getTime(); }
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + resInfo); return obj;
} }
return weixinMap;
} public static Map<String, Object> getHttpByGet(String url, String userName, String password , byte[] b) {
Map<String, Object> map = new HashMap<String, Object>();
public static Object getWinxinResByJsonToObj(String url, String jsonStr, Class clazz) { org.apache.http.client.HttpClient client = getHttpClient();
return getWinxinResByJsonToObj(url, jsonStr, clazz, "POST"); setIp(client,b) ;
} if (userName != null && password != null) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
public static Object getWinxinResByJsonToObj(String url, String jsonStr, Class clazz, String method) { UsernamePasswordCredentials usernamePassword = new UsernamePasswordCredentials(userName, password);
credsProvider.setCredentials(AuthScope.ANY, usernamePassword);
long begin = new Date().getTime(); ((AbstractHttpClient) client).setCredentialsProvider(credsProvider);
String resInfo = null; }
Object obj = null; HttpGet get = new HttpGet(url);
org.apache.http.client.HttpClient client = getHttpClient(); get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
HttpResponse response = null;
HttpResponse response = null; try {
response = client.execute(get);
try { map = doResponse(response);
if ("POST".equals(method)) { } catch (ClientProtocolException e) {
HttpPost post = new HttpPost(url); e.printStackTrace();
if (null != jsonStr) { } catch (IOException e) {
post.setEntity(new StringEntity(jsonStr, "utf-8")); e.printStackTrace();
} } finally {
response = client.execute(post); if (response != null) {
} try {
if ("GET".equals(method)) { response.getEntity().getContent().close();
HttpGet get = new HttpGet(url); } catch (IllegalStateException | IOException e) {
response = client.execute(get); e.printStackTrace();
} }
}
resInfo = EntityUtils.toString(response.getEntity(), "utf-8"); }
return map;
obj = JSON.parseObject(resInfo, clazz);
} catch (UnsupportedEncodingException e) { }
// TODO Auto-generated catch block
e.printStackTrace(); public static Map<String, Object> getHttpByGet(String url , byte[] b) {
} catch (ClientProtocolException e) { return getHttpByGet(url, null, null , b);
// TODO Auto-generated catch block }
e.printStackTrace();
} catch (IOException e) { private static Map<String, Object> doResponse(HttpResponse response) {
// TODO Auto-generated catch block Map<String, Object> map = new HashMap<String, Object>();
e.printStackTrace(); String line = "";
} finally { String result = null;
long end = new Date().getTime(); String responseStr = "";
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + jsonStr + " res:" + resInfo); int responseCode = 0;
} try {
return obj;
} HttpEntity entity = response.getEntity();
public static Map<String, Object> getWinxinResByFile(String url, Map<String, ContentBody> map) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
long begin = new Date().getTime(); StringBuilder builder = new StringBuilder();
String entityStr = null;
MultipartEntity entity = new MultipartEntity(); responseCode = response.getStatusLine().getStatusCode();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) { switch (responseCode) {
String keyString = iterator.next(); // 请求成功
entity.addPart(keyString, map.get(keyString)); case HttpURLConnection.HTTP_OK:
} while ((line = reader.readLine()) != null) {
builder.append(line);
Map<String, Object> obj = null; }
org.apache.http.client.HttpClient client = getHttpClient(); responseStr = builder.toString();
HttpPost post = new HttpPost(url); result = "请求成功";
StringBuilder builder = new StringBuilder(); break;
case HttpURLConnection.HTTP_BAD_REQUEST:
try { while ((line = reader.readLine()) != null) {
post.setEntity(entity); builder.append(line);
HttpResponse response = client.execute(post); }
entityStr = EntityUtils.toString(response.getEntity(), "utf-8"); responseStr = builder.toString();
result = "错误请求";
obj = JSON.parseObject(entityStr, Map.class); break;
} catch (Exception e) { case HttpURLConnection.HTTP_INTERNAL_ERROR:
// TODO Auto-generated catch block result = "服务器端错误";
e.printStackTrace(); break;
return new HashMap<String, Object>(); case HttpURLConnection.HTTP_NOT_FOUND:
} finally { result = "未找到指定的网址";
long end = new Date().getTime(); break;
logger.info("call-res cost:" + (end - begin) + " url:" + url + " param:" + map + " res:" + entityStr); case HttpURLConnection.HTTP_BAD_GATEWAY:
} result = "请求超时";
return obj; break;
} default:
break;
public static Map<String, Object> getWinxinRes(String url, Map<String, String> map) { }
Object obj = getWinxinRes(url, map, Map.class, "POST");
if (null != obj) } catch (Exception e) {
return (Map<String, Object>) obj; e.printStackTrace();
return null; map.put("code", HttpURLConnection.HTTP_BAD_GATEWAY);
} map.put("result", "无法连接网络,请检查网络设置");
map.put("response", "");
public static Map<String, Object> getWinxinRes(String url, Map<String, String> map, String method) { } finally {
Object obj = getWinxinRes(url, map, Map.class, method); map.put("code", responseCode);
if (null != obj) map.put("result", result);
return (Map<String, Object>) obj; map.put("response", responseStr);
return null; }
}
return map;
public static Object getWinxinRes(String url, Map<String, String> map, Class clazz) { }
return getWinxinRes(url, map, clazz, "POST"); private static void setIp(org.apache.http.client.HttpClient client , byte[] b) {
} try {
if(null != b) {
public static Object getWinxinRes(String url, Map<String, String> map, Class clazz, String method) { client.getParams().setParameter(ConnRouteParams.LOCAL_ADDRESS, InetAddress.getByAddress(b)) ;
long begin = System.currentTimeMillis(); }
} catch (UnknownHostException e2) {
String entityStr = null; // TODO Auto-generated catch block
Object obj = null; e2.printStackTrace();
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; package com.gic.qywx.self;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -15,6 +12,7 @@ import org.apache.http.entity.mime.content.ByteArrayBody; ...@@ -15,6 +12,7 @@ import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.ContentBody;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -28,41 +26,38 @@ public class QywxController { ...@@ -28,41 +26,38 @@ public class QywxController {
private static final Logger logger = LoggerFactory.getLogger(QywxController.class); private static final Logger logger = LoggerFactory.getLogger(QywxController.class);
@RequestMapping("self-post") @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); 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; return map;
} }
@RequestMapping("self-post-json") @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); 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; return map;
} }
@RequestMapping("self-get") @RequestMapping("self-get")
public Object selfGet(String url) { public Object selfGet(String url, String ip) {
logger.info("自建get,url={}", url); logger.info("自建get,url={}", url);
Map<String, Object> map = HttpClient.getHttpByGet(url); Map<String, Object> map = HttpClient.getHttpByGet(url, getIp(ip));
return map; return map;
} }
@RequestMapping("self-upload") @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); logger.info("自建upload,url={}", url);
byte[] data = CommonUtil.getFileByte(fileUrl); byte[] data = CommonUtil.getFileByte(fileUrl);
Map<String, ContentBody> paramsMap = new HashMap<String, ContentBody>(); Map<String, ContentBody> paramsMap = new HashMap<String, ContentBody>();
paramsMap.put("media", new ByteArrayBody(data, ContentType.DEFAULT_BINARY, fileName)); 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; return map;
} }
@RequestMapping("self-upload-data") @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); logger.info("自建upload-data,url={}", url);
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> list = multiRequest.getMultiFileMap().get("media"); List<MultipartFile> list = multiRequest.getMultiFileMap().get("media");
...@@ -70,8 +65,18 @@ public class QywxController { ...@@ -70,8 +65,18 @@ public class QywxController {
byte[] data = mf.getBytes(); byte[] data = mf.getBytes();
Map<String, ContentBody> paramsMap = new HashMap<String, ContentBody>(); Map<String, ContentBody> paramsMap = new HashMap<String, ContentBody>();
paramsMap.put("media", new ByteArrayBody(data, ContentType.DEFAULT_BINARY, fileName)); 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; 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