QRCodeUtils.java
@Component
public class QRCodeUtils {
private static final Logger LOG = LogManager.getLogger(QRCodeUtils.class);
private static final String APPID = "wxxxxxxxxx";
private static final String SECRET = "xxxxxxx";
private static final String GRANT_TYPE = "client_credential";
private static final String TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?";// 获取Token
private static final String URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";// 获取二维码
@Resource
HttpPost httpPost;
@Resource(name = "terminalupload")
private Properties terminalupload;
public void request(Long cid, Long pid, String imgpath) {
Map<String, Object> mapColor = new HashMap<>();
mapColor.put("r", "0");
mapColor.put("g", "0");
mapColor.put("b", "0");
Map<String, Object> requestMap = new HashMap<>();
String id = String.valueOf(cid);
requestMap.put("scene",id);
requestMap.put("page", "pages/main/main");
requestMap.put("width", 430);
requestMap.put("auto_color", false);
requestMap.put("line_color", null);// mapColor
// 发起请求
String response = "";
try {
String access_token = getToken();
response = httpPost.sendJsonObject2(URL + "?access_token=" + access_token, requestMap, pid, imgpath);
LOG.info("获取二维码:" + response);
} catch (Exception e) {
LOG.error("获取二维码失败!", e);
}
}
public String getToken() {
Map<String, Object> requestParam = new HashMap<>();
requestParam.put("appid", APPID);
requestParam.put("secret", SECRET);
requestParam.put("grant_type", GRANT_TYPE);
// 发起请求
String response = "";
try {
response = httpPost.sendJsonObject(TOKENURL + Joiner.on("&").withKeyValueSeparator("=").join(requestParam),
GsonUtil.toJson(requestParam));
LOG.info("Token:" + response);// access_token
JSONObject responseJson = JSONObject.fromObject(response);
return responseJson.optString("access_token");
} catch (Exception e) {
LOG.error("获取Token失败!", e);
}
return "";
}
HttpPost.java
/**
* @param httpUrl
* @param object
* @return
*/
public String sendJsonObject(final String httpUrl, final Object object) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
RequestBuilder requestBuilder = RequestBuilder.get().setUri(new URI(httpUrl))
.setConfig(Config.getRequestConfig());
// params
if (object == null) {
requestBuilder.setEntity(new StringEntity(GsonUtil.toJson(null), ContentType.APPLICATION_JSON));
}
HttpUriRequest httpUriRequest = requestBuilder.build();
response = httpClient.execute(httpUriRequest);
return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
} finally {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
/**
* @param httpUrl
* @param params
* @return
*/
public String sendJsonObject2(final String httpUrl, final Map<String, Object> params,Long pid,String imgUrl) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
FileOutputStream fout = null;
InputStream in = null;
String imgPath = String.valueOf(terminalupload.get("imgPath"));
String wxa = String.valueOf(terminalupload.get("wxa"));
String imgUrlAssembly = imgPath+wxa+pid+"/";
try {
httpClient = HttpClients.createDefault();
RequestBuilder requestBuilder = RequestBuilder.post().setUri(new URI(httpUrl))
.setConfig(Config.getRequestConfig());
// params
if (params != null && !params.isEmpty()) {
requestBuilder.setEntity(new StringEntity(GsonUtil.toJson(params), ContentType.APPLICATION_JSON));
}
HttpUriRequest httpUriRequest = requestBuilder.build();
response = httpClient.execute(httpUriRequest);
HttpEntity httpEntity=response.getEntity(); //4、获取实体
in = httpEntity.getContent();
File file = new File(imgUrlAssembly);
if(!file.exists()) {
file.mkdirs();
}
fout = new FileOutputStream(imgPath+wxa+imgUrl);
int l = -1;
byte[] tmp = new byte[1024];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
}
fout.flush();
fout.close();
in.close();
return "SUCCEES";
} finally {
// 关闭低层流。
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
Config.java
public class Config {
public static RequestConfig getRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(12000) // 设置连接超时时间,单位毫秒。
.setConnectionRequestTimeout(12000) // 设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
.setSocketTimeout(12000) // 请求获取数据的超时时间,单位毫秒。如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
.build();
}
public static CloseableHttpClient getHttpClients(final File sslJks, final String sslPwd) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(sslJks, sslPwd.toCharArray(),
new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom()
.setSSLSocketFactory(sslSf)
.build();
}
/**
* 忽略证书验证请求
*/
public static CloseableHttpClient createSSLClientDefault() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有证书
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslFactory).build();
}
}
GsonUtil.java
public class GsonUtil {
private static Gson GSON = new Gson();
public static <T> T fromJson(String json, Type type) {
return GSON.fromJson(json, type);
}
public static <T> T fromJson(String json, Class<T> classOfT) {
return GSON.fromJson(json, classOfT);
}
public static <T> T fromJsonp(String jsonp, Class<T> classOfT) {
String json = jsonp.substring(jsonp.indexOf("{"), jsonp.lastIndexOf("}") + 1);
return GSON.fromJson(json, classOfT);
}
public static String toJson(Object src) {
return GSON.toJson(src);
}
}