@RequestMapping("/getCode")
public void getCodeM(String id,HttpServletRequest request,HttpServletResponse reponse) throws Exception {
String token = getToken(); // 得到token
Map<String, Object> params = new HashMap<>();
params.put("scene", id); //参数
/* params.put("page", page); //位置
*/ params.put("width", 430);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token); // 接口
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params); //必须是json模式的 post
StringEntity entity;
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
IOUtils.copyLarge(inputStream, reponse.getOutputStream());
}
/*
* 获取 token
* 普通的 get 可获 token
*/
public String getToken() {
try {
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+readUtil.getString(RedisConstant.WECHAT + "wxspAppid")+ "&secret="+readUtil.getString(RedisConstant.WECHAT + "wxspSecret");
System.out.println("URL for getting accessToken accessTokenUrl="+accessTokenUrl);
URL url = new URL(accessTokenUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
//获取返回的字符
InputStream inputStream = connection.getInputStream();
int size =inputStream.available();
byte[] bs =new byte[size];
inputStream.read(bs);
String message=new String(bs,"UTF-8");
//获取access_token
JSONObject jsonObject = JSONObject.fromObject(message);
String accessToken = jsonObject.getString("access_token");
String expires_in = jsonObject.getString("expires_in");
System.out.println("accessToken="+accessToken);
System.out.println("expires_in="+expires_in);
return accessToken;
} catch (Exception e) {
log.error("# 获取 token 出错... e:" + e);
e.printStackTrace();
return null;
}
}