前言:
在做小程序的开发时需要获取用户的openId用来做唯一标识,来获取对应用户的相关数据
官方的文档说明上有四个必须传的参数
其中appId和appSecret可在自己的微信公众号平台上获取,同时这些也是属于私密信息,应该妥善保管的,因为微信手机客户端是很容易反编译获取到这些信息的,所以在前端的ajax请求将这些参数传到后台是不可取的,最好的方式是将这两个参数在后台传入,然后发送请求至官方接口
1.模拟Http请求
package com.btw.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.util.Map; public class HttpUtil { /** * 请求类型: GET */ public final static String GET = "GET"; /** * 请求类型: POST */ public final static String POST = "POST"; /** * 模拟Http Get请求 * @param urlStr * 请求路径 * @param paramMap * 请求参数 * @return * @throws Exception */ public static String get(String urlStr, Map<String, String> paramMap) throws Exception{ urlStr = urlStr + "?" + getParamString(paramMap); HttpURLConnection conn = null; try{ //创建URL对象 URL url = new URL(urlStr); //获取URL连接 conn = (HttpURLConnection) url.openConnection(); //设置通用的请求属性 setHttpUrlConnection(conn, GET); //建立实际的连接 conn.connect(); //获取响应的内容 return readResponseContent(conn.getInputStream()); }finally{ if(null!=conn) conn.disconnect(); } } /** * 模拟Http Post请求 * @param urlStr * 请求路径 * @param paramMap * 请求参数 * @return * @throws Exception */ public static String post(String urlStr, Map<String, String> paramMap) throws Exception{ HttpURLConnection conn = null; PrintWriter writer = null; try{ //创建URL对象 URL url = new URL(urlStr); //获取请求参数 String param = getParamString(paramMap); //获取URL连接 conn = (HttpURLConnection) url.openConnection(); //设置通用请求属性 setHttpUrlConnection(conn, POST); //建立实际的连接 conn.connect(); //将请求参数写入请求字符流中 writer = new PrintWriter(conn.getOutputStream()); writer.print(param); writer.flush(); //读取响应的内容 return readResponseContent(conn.getInputStream()); }finally{ if(null!=conn) conn.disconnect(); if(null!=writer) writer.close(); } } /** * 读取响应字节流并将之转为字符串 * @param in * 要读取的字节流 * @return * @throws IOException */ private static String readResponseContent(InputStream in) throws IOException{ Reader reader = null; StringBuilder content = new StringBuilder(); try{ reader = new InputStreamReader(in); char[] buffer = new char[1024]; int head = 0; while( (head=reader.read(buffer))>0 ){ content.append(new String(buffer, 0, head)); } return content.toString(); }finally{ if(null!=in) in.close(); if(null!=reader) reader.close(); } } /** * 设置Http连接属性 * @param conn * http连接 * @return * @throws ProtocolException * @throws Exception */ private static void setHttpUrlConnection(HttpURLConnection conn, String requestMethod) throws ProtocolException{ conn.setRequestMethod(requestMethod); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"); conn.setRequestProperty("Proxy-Connection", "Keep-Alive"); if(null!=requestMethod && POST.equals(requestMethod)){ conn.setDoOutput(true); conn.setDoInput(true); } } /** * 将参数转为路径字符串 * @param paramMap * 参数 * @return */ private static String getParamString(Map<String, String> paramMap){ if(null==paramMap || paramMap.isEmpty()){ return ""; } StringBuilder builder = new StringBuilder(); for(String key : paramMap.keySet() ){ builder.append("&") .append(key).append("=").append(paramMap.get(key)); } return builder.deleteCharAt(0).toString(); } }
其中请求参数已经封装成map的形式,非常方便
2.请求接口
在这个接口我们只需要接收一个code的参数,然后用String类型接收Util类返回的数据即可,其中的url为官方接口地址
package com.btw.controller; import com.btw.util.AppConstant; import com.btw.util.HttpUtil; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/system") public class SecretController { @RequestMapping(value = "/getOpenId",method = RequestMethod.GET) public String getOpenid(HttpServletRequest request,HttpServletResponse response, @RequestParam String code){ Map<String,String> paramMap=new HashMap<>(); paramMap.put("appid", AppConstant.AppId); paramMap.put("secret",AppConstant.AppSecret); paramMap.put("js_code",code); paramMap.put("grant_type","authorization_code"); String url="https://api.weixin.qq.com/sns/jscode2session"; String res=null; try { res=HttpUtil.post(url,paramMap); } catch (Exception e) { e.printStackTrace(); } return res; } }
3.前端Ajax请求
原文地址:https://www.cnblogs.com/wutongshu-master/p/11660552.html
时间: 2024-11-05 20:44:17