微信公眾平臺 ---------java實現二維碼帶參生成本地圖片(2017/11/10更新版)
學藝不精,百度好多資料都沒弄成功,總是少一些包啊,方法啊,還有一些類啊
於是參考各種典籍自己寫了一下,發現並不難.分享一下,雖然只是簡單的實現了功能 ,可能存在bug,不足之處希望大家能指點一下
關於post get http協議工具類
HttpRequest.java
package http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.io.DataOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
public class HttpRequest {
/**
* 向指定URL傳送GET方法的請求
*
* @param url
* 傳送請求的URL
* @param param
* 請求引數,請求引數應該是 name1=value1&name2=value2 的形式。
* @return URL 所代表遠端資源的響應結果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url +"?" + param;
// System.out.println("urlNameString==="+urlNameString);
URL realUrl = new URL(urlNameString);
// 開啟和URL之間的連線
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連線
connection.connect();
// 獲取所有響應頭欄位
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭欄位
for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("傳送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 傳送POST方法的請求
*
* @param url
* 傳送請求的 URL
* @param param
* 請求引數,請求引數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠端資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 開啟和URL之間的連線
URLConnection conn = realUrl.openConnection();
// 設定通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 傳送POST請求必須設定如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection物件對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 傳送請求引數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("傳送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static String appadd(String url2) {
// "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=NmkgW8j9YKEOfDRpODUcjIwhO2mAQHX8gct3JHp4YduvtwMNVyGRpuWaAT-tWM4p3-62SsNIhphlgpusyqry1q_Ueoz4S2TCn6RSJdA5uapf93JfWsZuFwJ_mBebrWOiMDBeAFABSQ";
String weixin_url = url2;
String ticke="";
try {
//建立連線
URL url = new URL(weixin_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
//POST請求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
String json = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
out.writeBytes(json);
out.flush();
out.close();
//讀取響應
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
ticke=sb.toString();
}
// System.out.println("ticke===="+sb);
reader.close();
// 斷開連線
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ticke;
}
}
關於帶參二維碼圖片下載本地, token 和ticke
GetErWeiMa.java
package http;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
public class GetErWeiMai {
/**
* 獲取token
* String appid
* String secret
* */
public static String token(){
String appid="wxf422109490024b6e";
String secret="eac80e067dcd92b301b3ae6c8eb3a1fb";
//傳送 GET 請求token
String url="https://api.weixin.qq.com/cgi-bin/token";
String s=HttpRequest.sendGet(url, "grant_type=client_credential&appid="+appid+"&secret="+secret);
int start = s.indexOf("\":\"");
int end = s.indexOf("\",\"");
String token = s.substring(start+3, end);
// System.out.println("token==>"+token);
return token;
}
/**
* 獲取ticke
* String token
* String
* */
public static String ticke( String token){
//傳送post 請求 ticke
String url2="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+token;
String a=HttpRequest.appadd(url2);
int start1= a.indexOf("\":\"");
int end1= a.indexOf("\",\"");
String ticke = a.substring(start1+3, end1);
// System.out.println("ticke>>>>>>>>>>"+ticke);
return ticke;
}
/**
* 獲取二維碼
* String tickefile
*
* String
* */
public static String toticke( String ticke){
//傳送 get 請求 換取二維碼 (ticke)
String url3="https://mp.weixin.qq.com/cgi-bin/showqrcode";
String tickefile=HttpRequest.sendGet(url3, "ticket="+ticke);
// System.out.println("filepath=="+url3+"?"+"ticket="+ticke);
return url3+"?"+"ticket="+ticke;
}
/**
* 連結url下載圖片
* String URL
*
**/
//連結url下載圖片
private static void downloadPicture(String urlList) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
//本地地址及名稱
String imageName = "E:/"+UUID.randomUUID()+".jpg";
FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
byte[] context=output.toByteArray();
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下載成功");
}
public static void main(String[] args) {
String url = GetErWeiMai.toticke(ticke(token()));
downloadPicture(url);
// System.out.println( test.toticke(ticke(token()))) ;
}
}簡單實現了帶參二維碼本地圖片下載 ,目前想到的存在問題:如何重複使用token以及token使用是出現失效情況
下面是一點個人更改,處理了重複使用token 和token失效的情況 ,暫時沒發現有什麼bug
package weixinStatic;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
public class GetErWeiMai {
static String token=""; // 傳給ticke 的引數 getAccess_Token
static String id="123"; // body傳的引數id
public static String APPID = "wxf422109490024b6e"; //公眾號 appid
public static String SECRET = "eac80e067dcd92b301b3ae6c8eb3a1fb"; //公眾號金鑰
public static void main(String[] args) {
String ticke; // ticke
if (GetErWeiMai.token==null||GetErWeiMai.token=="") {
GetErWeiMai.token=getAccess_token(); //根據引數獲取token
}
try {
ticke = getTicket(GetErWeiMai.token,id); //根據token 獲取ticke
} catch (Exception e) {
// TODO Auto-generated catch block
GetErWeiMai.token=getAccess_token(); //token 過期失效等情況
ticke = getTicket(GetErWeiMai.token,id); //重新獲取token 和ticke
e.printStackTrace();
}
String url = GetErWeiMai.toticke(ticke); //根據ticke 獲取二維碼url
downloadPicture(url); //下載二維碼
}
/**
* 獲取 token
* String appid
* String secret
* */
public static String getAccess_token() {
// 傳送 GET 請求token
String url = "https://api.weixin.qq.com/cgi-bin/token";
String s = HttpRequest.sendGet(url,
"grant_type=client_credential&appid=" + APPID + "&secret="+ SECRET);
int start = s.indexOf("\":\"");
int end = s.indexOf("\",\"");
String token = s.substring(start + 3, end);
return token;
}
/**
* 獲取ticke
* String token
* String id
* */
private static String getTicket(String token ,String id) {
// 傳送post 請求 ticke
System.out.println("token:"+token);
// 根據輸入token獲取ticke
String url2 = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;
String a = HttpRequest.appadd(url2,id);
System.out.println("微信伺服器獲取Ticket:"+a);
int start = a.indexOf("\":\"");
int end = a.indexOf("\",\"");
String b = a.substring(start + 3, end);
return b;
}
/**
* 獲取二維碼
* String tickefile
* */
public static String toticke(String ticke ) {
// 傳送 get 請求 換取二維碼 (ticke)
String url3 = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
String tickefile = HttpRequest.sendGet(url3, "ticket=" + ticke);
return url3 + "?" + "ticket=" + ticke;
}
/**
* 連結url下載圖片
* String URL
*
**/
// 連結url下載圖片
private static void downloadPicture(String urlList) {
URL url = null;
//int imageNumber = 0;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
// 本地地址及名稱
String imageName = "E:/" + UUID.randomUUID() + ".jpg";
FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
byte[] context = output.toByteArray();
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下載成功");
}
}