实操网站新闻分享微信显示缩略图

微信文档参考地址:概述 | 微信开放文档

实现网站新闻分享微信显示缩略图准备工作:

  • 准备备案的域名
  • 准备公众号
  • 配置公众号  ip白名单、js安全域名、开启secret

前端代码:





后台代码:

@RequestMapping(value="/getData")
@ResponseBody
public Map getData(HttpServletRequest req,HttpServletResponse response) throws IOException{
			 
			 response.setHeader("Access-Control-Allow-Origin", "*");
			 
			 String url = req.getParameter("url");
			 if ( url==null || "".equals(url) ) {
				 return null;
			 }
			 
			 /*1.获取access_token   有效期7200秒
			    参数	是否必须	说明
			 grant_type	是	获取access_token填写client_credential
			 appid	是	第三方用户唯一凭证
			 secret	是	第三方用户唯一凭证密钥,即appsecret
			 */
			 String appid="填写你的appid";
			 String secret ="填写你的secret";
			 
			 String token="";
			 
			 String ticket="";
			 
			 Object access_token = req.getSession().getAttribute("access_token");
			 if(access_token==null || "".equals(access_token)) {
				 String dataToken =  OkhttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token?",appid , secret);
				 JSONObject  jsonObject = JSON.parseObject(dataToken);
				 
				 if(jsonObject!=null) {
					 token = jsonObject.get("access_token").toString();
					 req.getSession().setAttribute("access_token", token);
					 req.getSession().setMaxInactiveInterval(7000);
				 }
			 }else {
				 token = access_token.toString();
			 }
			 
			 //2.使用access_token  采用http GET方式请求获得jsapi_ticket
			 Object ticket_session = req.getSession().getAttribute("ticket_session");
			 if(ticket_session==null || "".equals(ticket_session)) {
				 
				 String dataTicket =  OkhttpUtils.sendGetByToken("https://api.weixin.qq.com/cgi-bin/ticket/getticket?", token);
				 JSONObject  jsonObject = JSON.parseObject(dataTicket);
				 
				 if(jsonObject!=null) {
					 ticket = jsonObject.get("ticket").toString();
					 req.getSession().setAttribute("ticket_session", ticket);
					 req.getSession().setMaxInactiveInterval(7000);
				 }
				 
			 }else {
				 ticket = ticket_session.toString();
			 }
			 
			 //3.获取签名
			 Map map = OkhttpUtils.sign(ticket, url, appid);
			 
			 if(map!=null) {
				 return map;
			 }
			 
			 return null;
			 
			 
			 
		 }

Okhttp需要的jar包:

链接: https://pan.baidu.com/s/1LvahpG_gezZu7vvEcX_zkw?pwd=pcva 提取码: pcva 

OkhttpUtils类:

package com.ssm;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * okhttp  get post 请求
 * @author Administrator
 *
 */
public class OkhttpUtils {
	
	//获取token
	public static String sendGet(String url, String appid, String secret) throws IOException {
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		StringBuilder req = new StringBuilder();
		req.append(url);
		req.append("grant_type=client_credential").append("&");
		req.append("appid="+appid).append("&");
		req.append("secret="+secret).append("&");
		Request request = new Request.Builder()
		        .url(req.toString())
		        .method("GET", null)
		        .build();
		Response response = client.newCall(request).execute();
		return response.body().string();
 }
	
	
	//根据token获取 ticket
	public static String sendGetByToken(String url, String access_token) throws IOException {
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		StringBuilder req = new StringBuilder();
		req.append(url);
		req.append("access_token="+access_token).append("&");
		req.append("type=jsapi").append("&");
		Request request = new Request.Builder()
		        .url(req.toString())
		        .method("GET", null)
		        .build();
		Response response = client.newCall(request).execute();
		return response.body().string();
 }
	
public static String sendPost(String url, String access_token) throws IOException {
	
        OkHttpClient client = new OkHttpClient().newBuilder().build();
	    MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
	    RequestBody body = RequestBody.create(mediaType,"");
	    Request request = new Request.Builder()
	            .url(url)
	            .addHeader("Authorization","Bearer "+access_token)
	            .addHeader("Content-Type", "application/json")
	            .method("POST", body)
	            .build();
	    Response response = client.newCall(request).execute();
	    return response.body().string();
}

//获取签名
public static Map sign(String jsapi_ticket, String url,String appid) {
	Map ret = new HashMap();
	String nonce_str = "sjzfcstring";
	long timestamp =  System.currentTimeMillis() / 1000;
	String string1;
	String signature = "";

	// 注意这里参数名必须全部小写,且必须有序
	string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "×tamp=" + timestamp + "&url=" + url;
	System.out.println(string1);

	try {
		MessageDigest crypt = MessageDigest.getInstance("SHA-1");
		crypt.reset();
		crypt.update(string1.getBytes("UTF-8"));
		signature = byteToHex(crypt.digest());
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}

	ret.put("url", url);
	ret.put("jsapi_ticket", jsapi_ticket);
	ret.put("nonceStr", nonce_str);
	ret.put("timestamp", timestamp+"");
	ret.put("signature", signature);
	ret.put("appid",appid);

	return ret;
}

private static String byteToHex(final byte[] hash) {
	Formatter formatter = new Formatter();
	for (byte b : hash) {
		formatter.format("%02x", b);
	}
	String result = formatter.toString();
	formatter.close();
	return result;
}


}

效果查看:

实操网站新闻分享微信显示缩略图_第1张图片

你可能感兴趣的:(微信)