微信转发带图片和描述——JAVA
? 網上看了好多大佬的文章,發現都不太適合我這種小白來操作,so只能結合大部分代碼來自己操作,搗鼓了2天終于可以實現轉發帶著圖片和描述了,我認為的比較簡單的整個流程是這樣的(哪里不正確請大佬指教):通過api連接獲得access_token>通過access_token來換取jsapi(ticket)>獲取時間毫秒數/隨即字符串/動態獲取的url>把這四個參數放到str中并使用SHA1加密再傳到前臺即可,廢話不多說,開始代碼(servlet):
獲取token和ticket的類:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
?* 獲取token ?獲取ticket
?* @author Administrator
?*
?*/
public class JsapiTicketUtil {
public static String sendGet(String url, String charset, int timeout)
? ? {
? ? ? String result = "";
? ? ? try
? ? ? {
? ? ? ? URL u = new URL(url);
? ? ? ? try
? ? ? ? {
? ? ? ? ? URLConnection conn = u.openConnection();
? ? ? ? ? conn.connect();
? ? ? ? ? conn.setConnectTimeout(timeout);
? ? ? ? ? BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
? ? ? ? ? String line="";
? ? ? ? ? while ((line = in.readLine()) != null)
? ? ? ? ? { ? ? ??
? ? ? ? ? ? result = result + line;
? ? ? ? ? }
? ? ? ? ? in.close();
? ? ? ? } catch (IOException e) {
? ? ? ? ? return result;
? ? ? ? }
? ? ? }
? ? ? catch (MalformedURLException e)
? ? ? {
? ? ? ? return result;
? ? ? }
? ? ?
? ? ? return result;
? ? }
? ?/***
? ? * 獲取acess_token?
? ? * @return
? ? */
? ?public static String getAccessToken(){
? ? ?//獲取token
String acess_token ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你自己的appid";
? ? ? ? ? String token = sendGet(acess_token, "utf-8", 10000);
? ? ? ? ? return token;
? ?}
? /***
? ? * 獲取jsapiTicket
? ? */
? public static String getJSApiTicket(){?
? ? ? JsonParser jsonparer = new JsonParser();
? ? ? JsonObject json = null;
? ? ? JsonObject json2 = null;
? ? ? //獲取token
? ? ? String acess_token= getAccessToken();?
? ? ? json = jsonparer.parse(acess_token).getAsJsonObject();
? ? ? String access_token = json.get("access_token").getAsString();
? ? ??
? ? ? //獲取JsAPI
? ? ? String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi"; ?
? ? ? String backData=sendGet(urlStr, "utf-8", 10000); ?
? ? ? json2 = jsonparer.parse(backData).getAsJsonObject();
? ? ? String ticket = json2.get("ticket").getAsString();
? ? ? System.out.println(ticket);
? ? ? return ?ticket; ?? ? ? ??
? } ?
}
獲得隨機字符串類:
import java.util.UUID;
/**
?* 獲取隨即字符串
?* @author Administrator
?*
?*/
public class Create_nonce_str {
public static String create_nonce_str() {
return UUID.randomUUID().toString();
}
}
SHA1加密類
import java.security.MessageDigest;
/**
?* SHA1加密
?* @author Administrator
?*
?*/
public class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', ?
? ? ? ? ? ? ?'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; ?
private static String getFormattedText(byte[] bytes) { ?
? ? ? ?int len = bytes.length; ?
? ? ? ?StringBuilder buf = new StringBuilder(len * 2); ?
? ? ? ?// 把密文轉換成十六進制的字符串形式 ?
? ? ? ?for (int j = 0; j < len; j++) { ?
? ? ? ? ? ?buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]); ?
? ? ? ? ? ?buf.append(HEX_DIGITS[bytes[j] & 0x0f]); ?
? ? ? ?} ?
? ? ? ?return buf.toString(); ?
? ?} ?
?
? ?public static String encode(String str) { ?
? ? ? ?if (str == null) { ?
? ? ? ? ? ?return null; ?
? ? ? ?} ?
? ? ? ?try { ?
? ? ? ? ? ?MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); ?
? ? ? ? ? ?messageDigest.update(str.getBytes()); ?
? ? ? ? ? ?return getFormattedText(messageDigest.digest()); ?
? ? ? ?} catch (Exception e) { ?
? ? ? ? ? ?throw new RuntimeException(e); ?
? ? ? ?} ?
? ?} ?
}
處理和發送到前臺的dopost方法
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
String nonceStr ?= ?Create_nonce_str.create_nonce_str();
? ? ? ? ? ? ? ?//這個url一定要動態獲取,不能寫死
String url="http://"+req.getServerName()+req.getContextPath()+"/"; ?System.out.println("當前地址為:"+url);
String jsapi_ticket = JsapiTicketUtil.getJSApiTicket();
System.out.println("時間戳:"+timestamp+"隨即串:"+nonceStr+"ticket:"+jsapi_ticket);
//所有參數必須小寫且有序
String str = "jsapi_ticket=" + jsapi_ticket +
? ? ? ? ? ? ? ? "&noncestr=" + nonceStr +
? ? ? ? ? ? ? ? "×tamp=" + timestamp +
? ? ? ? ? ? ? ? "&url=" + url;
//sha1加密
? ? ? ? String signature = SHA1.encode(str);
? ? ? ? System.out.println("生成的簽名:"+signature);
? ? ? ? //將三個參數拼接成字符串到前臺,再由逗號分割取出
? ? ? ? String data = timestamp+","+nonceStr+","+signature;
? ? ? ? out.print(data);
? ? ? ? out.flush();
? ? ? ? out.close();
}
前臺代碼(我是寫在body中了):
<script type="text/javascript"
src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
window.οnlοad=function(){
????????????? ? //定義全局變量 ?接收后臺傳遞的三個參數
var nonceStr;
var signature;
$.ajax({
type : "POST",?
dataType : "text",?
url : "${ctx}/GainWXServlet.do",?
success : function(data) {
if (data != null) {
var arr=data.split(",");
timestamp = arr[0];
nonceStr = arr[1];
signature = arr[2];
wx.config({
? ?debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。
? ?appId: '你的id', // 必填,公眾號的唯一標識
? ?timestamp: timestamp, // 必填,生成簽名的時間戳
? ?nonceStr: nonceStr, // 必填,生成簽名的隨機串
? ?signature: signature,// 必填,簽名
? ?jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填,需要使用的JS接口列表
});
?wx.checkJsApi({
? ?jsApiList: ['chooseImage'], // 需要檢測的JS接口列表,所有JS接口列表見附錄2,
? ?success: function(res) {
? ?// 以鍵值對的形式返回,可用的api值true,不可用為false
? ?// 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
? ?}
});
?wx.onMenuShareTimeline({
? ?title: '分享標題', // 分享標題
? ?link: '分享鏈接', // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
? ?imgUrl: '分享圖標', // 分享圖標
? ?success: function () {
? ?// 用戶點擊了分享后執行的回調函數
}});
wx.onMenuShareAppMessage({
title: '', // 分享標題
desc: '', // 分享描述
link: 'http://fifa.dlscanyin.com/', // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: 'http://fifa.dlscanyin.com/images/logo.jpg', // 分享圖標
type: '', // 分享類型,music、video或link,不填默認為link
dataUrl: '', // 如果type是music或video,則要提供數據鏈接,默認為空
success: function () {
// 用戶點擊了分享后執行的回調函數
}
});
} else {
alert("數據沒有獲取到哦~");
}
}
});
};
</script>
PS:如果發生
{errmsg:config: invalid signature}
首先檢查去微信的這個鏈接:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign,將自己的代碼中的數據和它的數據做對比,如果還有問題,請檢查url錯誤,可能最后的一個"/"都能引起這個錯誤,最后說下,我的代碼比較簡單,里面肯定有很多不合理的地方,請大佬多多指教
總結
以上是生活随笔為你收集整理的微信转发带图片和描述——JAVA的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习实战-微额借款用户人品预测
- 下一篇: Microsoft Academic S