|
作者:lay2016,來(lái)自原文地址
在使用小程序提供的API: createwxaqrcode的時(shí)候,后臺(tái)獲取的返回值是一些像亂碼的東西。
其實(shí)這些東西是二維碼的數(shù)據(jù)流,而且是沒(méi)有經(jīng)過(guò)base64加密過(guò)的。
所以不需要經(jīng)過(guò)base64解密。
直接將數(shù)據(jù)流保存為JPG或者PNG圖片就可以了。
但是怎么保存呢?
我這里提供一下項(xiàng)目中的Java代碼:
-
/**
-
* 獲取二維碼請(qǐng)求
-
* @param request
-
* @param url
-
* @param params
-
* @return 返回二維碼地址
-
*/
-
public static String getQRCode(HttpServletRequest request, String url, String params){
-
System.out.println("地址:" + url);
-
System.out.println("參數(shù):" + params);
-
-
HttpClient client = new DefaultHttpClient();
-
HttpPost post = new HttpPost(url);
-
-
post.setHeader("Content-Type", "application/json");
-
post.addHeader("Authorization", "Basic YWRtaW46");
-
String result = "";
-
-
try {
-
-
StringEntity s = new StringEntity(params, "utf-8");
-
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
-
"application/json"));
-
post.setEntity(s);
-
-
// 發(fā)送請(qǐng)求
-
HttpResponse httpResponse = client.execute(post);
-
-
// 獲取響應(yīng)輸入流
-
InputStream inStream = httpResponse.getEntity().getContent();
-
String savePath = request.getSession().getServletContext().getRealPath("upload/code");
-
String fileName = new GuidUtils().newGuid();
-
String fileExt = ".jpg";
-
// 如果沒(méi)有該路徑,那么創(chuàng)建一個(gè)
-
File file = new File(savePath);
-
if (!file.exists()){
-
file.mkdirs();
-
}
-
saveImgInStream(inStream, savePath, fileName, fileExt);
-
result = "/upload/code/" + fileName + fileExt;
-
} catch (Exception e) {
-
System.out.println("請(qǐng)求異常");
-
throw new RuntimeException(e);
-
}
-
return result;
-
}
-
-
/**
-
* 將輸入流保存為圖片
-
* @param stream 輸入流
-
* @param savePath 存儲(chǔ)路徑
-
* @param fileName 文件名
-
* @param fileExt 格式
-
* @throws Exception
-
*/
-
public static void saveImgInStream(InputStream stream, String savePath, String fileName, String fileExt) throws Exception{
-
// 將輸入流保存為圖片
-
byte[] data = new byte[1024];
-
int len = 0;
-
FileOutputStream fileOutputStream = null;
-
String path = savePath + "\\" + fileName + fileExt;
-
fileOutputStream = new FileOutputStream(path);
-
while ((len = stream.read(data)) != -1) {
-
fileOutputStream.write(data, 0, len);
-
}
-
// 關(guān)閉流
-
fileOutputStream.close();
-
}
省略了不少代碼,僅供參考
|