小程序生成外链【url_link】版
代码
package com.farbun.fission.util;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
@Component
public class UrlLinkUtil {
@Value("${wx.WeChat.AppID}")
private String appid;
@Value("${wx.WeChat.AppSecret}")
private String secret;
@Value("${wx.WeChat.AppMiniPath}")
private String path;
public String getAccessToken() {
String url = String.format(ApiUrl.miniAppToken, appid, secret);
try {
return performHttpRequest(url);
} catch (Exception e) {
log.info("HTTP请求失败: {}" , e.getMessage());
}
return "";
}
public String jumpAppletShortUrl(String query) {
String accessToken = getAccessToken();
JSONObject resultObject = new JSONObject(accessToken);
String AccessToken = resultObject.getString("access_token");
String linkUrl = String.format(ApiUrl.miniAppLink, AccessToken);
JSONObject requestBody = new JSONObject();
requestBody.put("path", path);
requestBody.put("query", query);
requestBody.put("expire_type", 1);
requestBody.put("expire_interval", 30);
requestBody.put("env_version", "release");
try {
String response = performHttpPost(linkUrl, requestBody.toString());
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("url_link")) {
return jsonObject.getString("url_link");
} else {
log.info("JSON响应中没有url_link字段");
return "";
}
} catch (Exception e) {
log.info("发生异常: {}" ,e.getMessage());
return "";
}
}
public String performHttpRequest(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "";
}
}
public String performHttpPost(String url, String requestBody) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(requestBody);
wr.flush();
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "";
}
}
}