https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115javascript
根據微信說明文檔步驟:(1)綁定域名[略](2)引入js文件[略]css
(3)經過config接口注入權限驗證配置:前端
頁面代碼:java
<script type="text/javascript"> function jssdk() { $.ajax({ url : '<%=basePath%>wx/jssdk.do',//調用java後臺獲取config配置信息:appid、timestamp 、nonceStr 、signature type : 'post', dataType : 'json', //contentType : "application/x-www-form-urlencoded; charset=utf-8", data : { 'url' : location.href.split('#')[0] }, success:function(data) { wx.config({ debug : true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 appId : data.appId, timestamp : data.timestamp, nonceStr : data.nonceStr, signature : data.signature, jsApiList : ['chooseImage','previewImage', 'uploadImage', 'downloadImage'] }); } }); } window.onload = function() { jssdk(); }; </script> |
後臺獲取jssdk配置信息:ajax
@RequestMapping(value = "/jssdk" , method = {RequestMethod.POST }) /** |
配置成功後,調用上傳圖片接口:服務器
HTML代碼:微信
<form class="signup" role="form">網絡 <div class="tit-set"> </form>
<script type="text/javascript"> |
調用上傳圖片接口後,須要將此圖片存到本身的圖片服務器時,須要將mediaId即images.serverId提交給java後臺接口,後臺接口接收到mediId後,調用微信獲取臨時素材接口:
public static void main(String[] args) throws Exception { // String token = TokenThread.accessToken.getToken(); String requrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; String url = requrl.replace("ACCESS_TOKEN", "HkAKN1zhEhIJvJ2iFHSxKBxD2i86IGe2lVVirE7iDFsSX3PeN-0mJ1wF4mTDP8Dibkv2ievaDLXUlzz6pE2hJHJ4uc6OD-jnTbsmDL1PyrFycpCMgQZ-yMW5eMepYkK1HFObACALJS").replace("MEDIA_ID", "iLXQnxsZYqjij_F3uwYMKXGM7ugE76yYkGZSxTIDCmY5ARujVBxe_9dEZUH80bRa"); InputStream inputStream = null; HttpURLConnection httpURLConnection = null; URL u = new URL(url);//建立的URL httpURLConnection = (HttpURLConnection) u.openConnection();//打開連接 httpURLConnection.setConnectTimeout(3000);//設置網絡連接超時時間,3秒,連接失敗後從新連接 httpURLConnection.setDoInput(true);//打開輸入流 httpURLConnection.setRequestMethod("GET");//表示本次Http請求是GET方式 int responseCode = httpURLConnection.getResponseCode();//獲取返回碼 if (responseCode == 200) {//成功爲200 //從服務器得到一個輸入流 inputStream = httpURLConnection.getInputStream(); } byte[] data = new byte[1024]; int len = 0; FileOutputStream fio = null; try { fio = new FileOutputStream("D:\\demo.jpg"); while ((len = inputStream.read(data)) != -1) { fio.write(data, 0, len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fio != null) { try { fio.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |