1. 程式人生 > 實用技巧 >微信公眾號獲取token,上傳素材

微信公眾號獲取token,上傳素材

public static JSONObject getToken(String appId,String appSecret){
         String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
         HttpURLConnection con = null;
         BufferedReader bufferedReader=null;
         try {
             URL urlObj 
= new URL(url); // 開啟連線 con = (HttpURLConnection) urlObj.openConnection(); // 設定請求通用引數 con.setRequestProperty("accept", "*/*"); con.setRequestProperty("connection", "Keep-Alive"); con.connect(); bufferedReader = new
BufferedReader(new InputStreamReader(con.getInputStream())); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { buffer.append(line); } String result
= buffer.toString(); JSONObject resultJSON = new JSONObject(result); if (resultJSON != null) { System.out.println(resultJSON.toString()); if(null!=resultJSON.get("access_token")) { return resultJSON; }else { throw new Exception("獲取微信token失敗,APPID="+appId+";微信訊息:"+resultJSON.getString("errmsg")+",code="+resultJSON.getString("errcode")); } } } catch (Exception e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if(null!=con) { con.disconnect(); } } return null; } /** * 傳送請求 * @Desc */ public static String connectHttpsByPost(String url,String token,String type, String KK, File file) throws Exception { if(token==null) { token = getToken("1111", "1111").get("access_token").toString(); } String path = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" + token; path = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + token; URL urlObj = new URL(path); //連線 HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); String result = null; con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false);// post方式不能使用快取 // 設定請求頭資訊 con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // 設定邊界 String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY); // 請求正文資訊 // 第一部分: StringBuilder sb = new StringBuilder(); sb.append("--"); // 必須多兩道線 sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // 獲得輸出流 OutputStream out = new DataOutputStream(con.getOutputStream()); // 輸出表頭 out.write(head); // 檔案正文部分 // 把檔案已流檔案的方式 推入到url中 DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // 結尾部分 if(null!=KK) { out.write(("--" + BOUNDARY + "\r\n").getBytes()); out.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes("utf-8")); out.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}",file.getName(),file.getName()).getBytes("utf-8")); } byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後資料分隔線 out.write(foot); out.flush(); out.close(); StringBuffer buffer = new StringBuffer(); BufferedReader reader = null; try { // 定義BufferedReader輸入流來讀取URL的響應 reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } if (result == null) { result = buffer.toString(); } } catch (IOException e) { System.out.println("傳送POST請求出現異常!" + e); e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } return result; }