微信定位分享工具类
程序员文章站
2022-03-18 20:42:30
...
/**
* 微信定位
* 分享链接
*/
import net.sf.json.JSONObject;
@GetMapping("/auth/getLocation")
public Wrapper getLocation( String locationUrl, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String urls=locationUrl;
String url = URLDecoder.decode(urls, "UTF-8");
//获取ticket 可以从redis中获取,也可以从数据库中获取
String ticket="";
log.info("ticket========================="+ticket);
JSONObject ret = TicketSignature.sign(ticket, url);
String nonceStr=(String) ret.get("nonceStr");
String timestamp=(String) ret.get("timestamp");
String websignature=(String) ret.get("signature");
Signature signature =new Signature();
signature.setNoncestr(nonceStr);
signature.setSignature(websignature);
signature.setTimestamp(timestamp);
return new Wrapper(200,"OK",signature);
return new Wrapper(400,"从redis获取token失败");
}
签名工具
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class TicketSignature extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(req, resp);
}
public static JSONObject sign(String jsapi_ticket, String url) {
JSONObject ret = new JSONObject();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
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")); // 对string1 字符串进行SHA-1加密处理
signature = byteToHex(crypt.digest()); // 对加密后字符串转成16进制
} 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);
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;
}
// 生成随机字符串
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
// 生成时间戳字符串
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
上一篇: CDR怎么制作彩色涂鸦字效果?
下一篇: freemarker中文乱码的解决