JAVA调⽤接⼝实现页⾯分享功能(分享到朋友圈显⽰图⽚,分享给朋友)钉钉提供的内⽹穿透之HTTP穿透:
⽹页分享到中如何显⽰标题图,如果⾃定义标题图,描述,显⽰效果如下
官⽹接⼝地址;
加⼊maven依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>[4.1.12,)</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
HttpClientUtil.java
st.cms.share;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.MalformedURLException;
import java.URI;
import java.URL;
import java.URLConnection;
import CertificateException;
import X509Certificate;
import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import org.apachemons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.ssl.SSLConnectionSocketFactory;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
private static class SingletonHolder{
private final static  HttpClientUtil INSTANCE=new HttpClientUtil();
}
private HttpClientUtil(){}
public static HttpClientUtil getInstance(){
return SingletonHolder.INSTANCE;
}
public  String get(String url){
CharsetHandler handler = new CharsetHandler("UTF-8");
CloseableHttpClient client = null;
try {
HttpGet httpget = new HttpGet(new URI(url));
HttpClientBuilder httpClientBuilder = ate();
client= httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
ute(httpget, handler);
} catch (Exception e) {
//e.printStackTrace();
return "";
}finally {
try {
if(client!=null){
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
public static String post(String url, String params,String contentType)
{
//创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = ate();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
CloseableHttpResponse res = null;
try
{
StringEntity s = new StringEntity(params,"UTF-8");
if(StringUtils.isBlank(contentType)){
s.setContentType("application/json");
}
s.setContentType(contentType);
s.setContentEncoding("utf-8");
post.setEntity(s);
res = ute(post);
HttpEntity entity = Entity();
String(entity, "utf-8");
}
catch (Exception e)
{
e.printStackTrace();
} finally {
try {
res.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public static String post(String urlStr,String xmlInfo) {
String line1 = "";
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setDoOutput(true);
//con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter out = new OutputStreamWriter(con
.getOutputStream());
out.write(new Bytes("utf-8")));
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream()));
String line = "";
for (line = br.readLine(); line != null; line = br.readLine()) {
line1+=line;
}
return new Bytes(),"utf-8");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private class CharsetHandler implements ResponseHandler<String> {
private String charset;
public CharsetHandler(String charset) {
this.charset = charset;
}
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = StatusLine();
if (StatusCode() >= 300) {
throw new StatusCode(),
}
HttpEntity entity = Entity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
String(entity, charset);
} else {
String(entity);
}
} else {
return null;
}
}
}
private static  HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = Instance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1" }, null,                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception ex) {
return null;
}
RandomStr.java
st.cms.share;
import java.util.Random;
public class RandomStr {
private static char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '0', '1' };//最后⼜重复两个0和1,因为需要凑⾜数组长度为64
private static Random random = new Random();
//⽣成指定长度的随机字符串
public static String createRandomString(int length) {
if (length > 0) {
int index = 0;
char[] temp = new char[length];
int num = Int();
for (int i = 0; i < length % 5; i++) {
temp[index++] = ch[num & 63];//取后⾯六位,记得对应的⼆进制是以补码形式存在的。
num >>= 6;//63的⼆进制为:111111
// 为什么要右移6位?因为数组⾥⾯⼀共有64个有效字符。为什么要除5取余?因为⼀个int型要⽤4个字节表⽰,也就是32位。            }
for (int i = 0; i < length / 5; i++) {
num = Int();
for (int j = 0; j < 5; j++) {
temp[index++] = ch[num & 63];
num >>= 6;
}
}
return new String(temp, 0, length);
}
else if (length == 0) {
return "";
}
else {
throw new IllegalArgumentException();
}
}
public static void main(String[] args) {
System.out.println(createRandomString(16));
}
}
Sha1.java
st.cms.share;
import java.security.MessageDigest;
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]);
}
String();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = Instance("SHA1");
messageDigest.Bytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
控制器类
ShareController.java
st.cms.share;
import cn.hutool.json.JSONUtil;
import org.apachemons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.hods.HttpGet;
import org.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import java.io.IOException;
import java.URI;
import CertificateException;
import X509Certificate;
import java.util.HashMap;
import java.util.Map;
@Controller
public class ShareController {
/**
* 的appid
*/
private String appid="wxd";
/**
* 的appSecret
*/
private String secret="ebded33";
/**
* 这是跳转到分享的页⾯
* @return
*/
@RequestMapping(value = "/to_detail")
public String share(){
return "/index/share";
}
/**
* 获取分享配置的请求⽅法只写了主要⽅法,需要根据⾃⼰的要求完善代码
* @param url 前台传过来的当前页⾯的请求地址
* @return
*/
@RequestMapping(value = "/get_wx_config")
@ResponseBody
public String share(String url){
long timestamp = System.currentTimeMillis() / 1000;
String noncestr = ateRandomString(16);
String ticket =getJsapiTicket();
String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
System.out.println("签名str:" + str);
String signature = de(str);
//这只是简单写法,没有做错误判断
Map map=new HashMap();
map.put("appId",appid);
map.put("timestamp",timestamp);
map.put("nonceStr",noncestr);
map.put("signature",signature);
//这⾥使⽤了hutool⼯具将map转为String
String json = JsonStr(map);
return json;
}
/**
* 官⽅⽂档:developers.weixin.qq/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
*
* 获取jsapi_ticket
*
*
*  ⽣成签名之前必须先了解⼀下jsapi_ticket,jsapi_ticket是⽤于调⽤JS接⼝的临时票据。
*  正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。
*  由于获取jsapi_ticket的api调⽤次数⾮常有限,频繁刷新jsapi_ticket会导致api调⽤受限,影响⾃⾝业务,开发者必须在⾃⼰的服务全局缓存jsapi_ticket 。    *
* 参考以下⽂档获取access_token(有效期7200秒,开发者必须在⾃⼰的服务全局缓存access_token):
* developers.weixin.qq/doc/offiaccount/Basic_Information/Get_access_token.html
*
* ⽤第⼀步拿到的access_token 采⽤http GET⽅式请求获得jsapi_ticket(有效期7200秒,开发者必须在⾃⼰的服务全局缓存jsapi_ticket):
* api.weixin.qq/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
*
* @return
*/
public String getJsapiTicket() {
String tokenUrl = "api.weixin.qq/cgi-bin/token?grant_type=client_credential";
tokenUrl = tokenUrl + "&appid=" + appid + "&secret=" + secret;
JSONObject tokenJson=new JSONObject();
tokenJson=getUrlResponse(tokenUrl);
System.out.println("tokenJson:"+String());
String token="";
try {
String("access_token");
} catch (JSONException e) {
e.printStackTrace();
System.out.println("报错了");
return null;
}
String jsapiTicketUrl="api.weixin.qq/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
JSONObject jsapiTickeJson=new JSONObject();
System.out.println("getJsapiTicket:获取token:"+token);
if(StringUtils.isNotBlank(token)){
jsapiTicketUrl = place("ACCESS_TOKEN",token);
jsapiTickeJson=getUrlResponse(jsapiTicketUrl);
System.out.println("tokenJson:"+String());
try {
return (String) ("ticket");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}else{
return null;
}
}
private  JSONObject getUrlResponse(String url){
CharsetHandler handler = new CharsetHandler("UTF-8");
try {
HttpGet httpget = new HttpGet(new URI(url));
HttpClientBuilder httpClientBuilder = ate();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
return new ute(httpget, handler));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = Instance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
代码转换SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception ex) {
return null;
}
}
private class CharsetHandler implements ResponseHandler<String> {
private String charset;
public CharsetHandler(String charset) {
this.charset = charset;
}
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = StatusLine();
if (StatusCode() >= 300) {
throw new StatusCode(),
}
HttpEntity entity = Entity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
String(entity, charset);
} else {
String(entity);
}
} else {
return null;
}
}
}
}
页⾯主要代码、这⾥展⽰的是分享给朋友、分享到朋友圈代码,其他分享可以具体看官⽅接⼝代码
share.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分享页⾯给朋友,朋友圈</title>
</head>
<body>
</body>
<script src="libs.baidu/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="res.wx.qq/open/js/jweixin-1.4.0.js"></script>
<script type="text/javascript">
$(function () {
//当前页⾯的url地址
var currUrl = decodeURIComponent(location.href.split('#')[0]);
$.ajax({
url: "/get_wx_config",
dataType : "json",
data: {
'url': currUrl
},
error: function (res) {
console.log(res);
alert("发⽣错误");
},
success: function (res) {
console.log(res);
var appId = res.appId;
var nonceStr = Str;
var timestamp = res.timestamp;
var signature = res.signature;
debug: false, //开启调试模式,开发阶段可以改成true,调⽤的所有api的返回值会在客户端alert出来,
若要查看传⼊的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。                    appId: appId, //必填,的唯⼀标识
timestamp: timestamp, // 必填,⽣成签名的时间戳
nonceStr: nonceStr, //必填,⽣成签名的随机串
signature: signature, // 必填,签名,见附录1
jsApiList: [            //必填,需要使⽤的JS接⼝列表,所有JS接⼝列表见附录2
'updateAppMessageShareData',
'updateTimelineShareData'
]
});

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。