Commit 9a381b2c by 徐高华

1

parent 95828bf9
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>gic-qywx-self</artifactId>
<groupId>com.gic</groupId>
<packaging>jar</packaging>
<description>self</description>
<version>1.0</version>
<name>self</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.1.RELEASE</version>
<exclusions>
<!--<exclusion> -->
<!--<groupId>ch.qos.logback</groupId> -->
<!--<artifactId>logback-classic</artifactId> -->
<!--</exclusion> -->
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.14.sec10</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
<build>
<finalName>gic-qywx-self</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.5.RELEASE</version>
<configuration>
<mainClass>com.gic.qywx.self.Main</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.gic.qywx.self;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
public class CommonUtil {
private static final Logger logger = getLogger(CommonUtil.class);
public static byte[] getFileByte(String url) {
try (InputStream in = new URL(url).openStream()) {
return IOUtils.toByteArray(in);
} catch (Exception e) {
logger.info("【异常】{} ,{},{}", e.getMessage(), e, url);
}
return null;
}
}
\ No newline at end of file
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 org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
/**
*
* @ClassName: Main
* @Description: TODO(这里用一句话描述这个类的作用)
* @author xugh
* @date 2020年9月9日 下午1:51:44
*
*/
@SpringBootApplication(scanBasePackages = "com.gic")
@ImportResource(value = { "classpath*:web-spring.xml" })
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
\ No newline at end of file
package com.gic.qywx.self;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.entity.ContentType;
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.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/qywx")
public class QywxController {
private static final Logger logger = LoggerFactory.getLogger(QywxController.class);
@RequestMapping("self-post")
public Object selfPost(String url, String json) {
logger.info("自建post,url={},json={}", url, json);
Map<String, Object> map = HttpClient.getWinxinResByJson(url, json);
return map;
}
@RequestMapping("self-post-json")
public Object selfPostJson(String url, @RequestBody String json) {
logger.info("自建post json,url={},json={}", url, json);
Map<String, Object> map = HttpClient.getWinxinResByJson(url, json);
return map;
}
@RequestMapping("self-get")
public Object selfGet(String url) {
logger.info("自建get,url={}", url);
Map<String, Object> map = HttpClient.getHttpByGet(url);
return map;
}
@RequestMapping("self-upload")
public Object selfUpload(String url, String fileUrl, String fileName) {
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);
return map;
}
}
package com.gic.qywx.self;
/**
* Created 2020/5/7.
*
* @author hua
*/
public enum QywxMediaTypeEnum {
IMAGE(0, "image"), VOICE(1, "voice"), VIDEO(2, "video"), FILE(3, "file"), LINK(4, "link"), MINIPROGRAM(5,
"miniprogram"),;
private int code;
private String name;
QywxMediaTypeEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static String getName(int code) {
QywxMediaTypeEnum[] values = QywxMediaTypeEnum.values();
for (QywxMediaTypeEnum mediaTypeEnum : values) {
if (mediaTypeEnum.getCode() == code) {
return mediaTypeEnum.getName();
}
}
return null;
}
}
server:
port: 8601
servlet:
context-path: /api-qywx-self
tomcat:
uri-encoding: UTF-8
spring:
jackson:
serialization:
# 以时间戳返回日期
write-dates-as-timestamps: true
http:
encoding:
charset: UTF-8
enabled: true
force: true
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>自建</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div class="container" id="couponDiv">
<h1>自建</h1>
</div>
</body>
</html>
\ No newline at end of file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
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