第一步:先获取AccessToken https写法
/**
*
*@Params: []
*@Date: 2018/5/16 11:35
*@Author: jinghan
*/
public static String getAccessToken(){
String appid = Configure.getAppid();
String appsecret = Configure.getAppSecret();
String requestUrl=access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
JSONObject jsonObject=httpRequst(requestUrl, "GET", null);
return jsonObject.getString("access_token");
}
/**
*
*@Params: [requestUrl, requetMethod, outputStr]
*@Date: 2018/5/16 11:37
*@Author: jinghan
*/
public static JSONObject httpRequst(String requestUrl,String requetMethod,String outputStr){
JSONObject jsonobject=null;
StringBuffer buffer=new StringBuffer();
try
{
//创建SSLContext对象,并使用我们指定的管理器初始化
TrustManager[] tm={new MyX509TrustManager()};
SSLContext sslcontext=SSLContext.getInstance("SSL","SunJSSE");
sslcontext.init(null, tm, new java.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocktFactory对象
SSLSocketFactory ssf=sslcontext.getSocketFactory();
URL url=new URL(requestUrl);
HttpsURLConnection httpUrlConn=(HttpsURLConnection)url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requetMethod);
if("GET".equalsIgnoreCase(requetMethod)) {
httpUrlConn.connect();
}
//当有数据需要提交时
if(null!=outputStr)
{
OutputStream outputStream=httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
InputStream inputStream=httpUrlConn.getInputStream();
InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String str=null;
while((str = bufferedReader.readLine()) !=null)
{
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream=null;
httpUrlConn.disconnect();
jsonobject=JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
// TODO: handle exception
}
catch (Exception e) {
}
return jsonobject;
}
第二步:根据token创建url 填充数据map 获取图片流
/**
*获取 数据流
*@Params: [url, map]
*@Date: 2018/5/15 15:34
*@Author: jinghan
*/
public static byte[] doImgPost(String url, Map<String,Object> map){
byte[] result = null;
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
try {
// 设置请求的参数
JSONObject postData = new JSONObject();
for (Map.Entry<String, Object> entry : map.entrySet()) {
postData.put(entry.getKey(), entry.getValue());
}
httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toByteArray(entity);
} catch (ConnectionPoolTimeoutException e) {
logger.error("http get throw ConnectionPoolTimeoutException(wait time out)", e);
} catch (ConnectTimeoutException e) {
logger.error("http get throw ConnectTimeoutException", e);
} catch (SocketTimeoutException e) {
logger.error("http get throw SocketTimeoutException", e);
} catch (Exception e) {
logger.error("http get throw Exception", e);
} finally {
httpPost.releaseConnection();
}
return result;
}
第三步:结合以上方法 输出图片数据流
/**
* 根据律师id 生成小程序码
*
* @Params:
* @Date: 2018/5/15 15:02
* @Author: jinghan
*/
@RequestMapping(value = "/smallProgramCode", produces = "text/html;charset=utf-8")
public void smallProgramCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
//获取律师id
String lawyerId = request.getParameter("lawyer_id");
//获取AccessToken
String accessToken = WeixinController.getAccessToken();
//组装url
String url = Const.WX_SMALLPROGRAMCODE + accessToken;
//组装参数
Map<String, Object> paraMap = new HashMap();
//二维码携带参数 不超过32位
paraMap.put("scene", lawyerId);
//二维码跳转页面
paraMap.put("path", "pages/lawyer_info/lawyer_info");
paraMap.put("width", "250");
paraMap.put("auto_color", false);
paraMap.put("line_color", "{\"r\":\"0\",\"g\":\"0\",\"b\":\"0\"}");
//执行post 获取数据流
byte[] result = HttpService.doImgPost(url, paraMap);
//输出图片到页面
PrintWriter out = response.getWriter();
InputStream is = new ByteArrayInputStream(result);
int a = is.read();
while (a != -1) {
out.print((char) a);
a = is.read();
}
out.flush();
out.close();
}
第四步:小程序页面添加图片链接(第三步中的接口携带参数) 即可在小程序页面看到二维码
<view class='nxcx'>
<image src="http://localhost:8080/smallProgramCode?lawyer_id=jinghan"></image>
<text class='ntxt'>小程序码</text>
</view>