文章目录
- 介绍
- 1、获取code并向服务器发送请求
- 2、引入发送HTTP请求的maven依赖
- 3、封装HTTP请求工具类
- 4、编写控制器
介绍
注意事项:- 必须是
GET
请求 - 微信发送的
code
码只能使用一次
1、获取code并向服务器发送请求
注:http://localhost:8080/portal/blog/app/login
对应第4步的控制器
wx.login({success (res) {console.log(res);if (res.code) {//发起网络请求wx.request({url: 'http://localhost:8080/portal/blog/app/login', //自己服务器的地址data: {code: res.code //向自己服务器传递的code参数},method:'POST', //记得是post请求success(res){console.log(res);}})} else {console.log('登录失败!' + res.errMsg)}}})
2、引入发送HTTP请求的maven依赖
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
</dependency><!-- JSON工具类 -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>
3、封装HTTP请求工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;import java.io.IOException;
import java.util.HashMap;/*** 微信登录,获取openid* @author XinLiu*/
@Component
public class WxHttpClient {private final static String BASE_URL = "https://api.weixin.qq.com/sns/jscode2session";private final static String appid = "自己的appid ";private final static String secret = "自己的secret ";public static HashMap<String, String> get(String appid, String secret, String code) throws IOException {String url = BASE_URL +"?appid=" +appid +"&secret=" +secret +"&js_code=" +code +"&grant_type=authorization_code";HttpGet httpGet = new HttpGet(url);CloseableHttpClient client = HttpClients.createDefault();CloseableHttpResponse response = client.execute(httpGet);HttpEntity entity = response.getEntity();String s = EntityUtils.toString(entity);JSONObject object = JSON.parseObject(s);String session_key = (String) object.get("session_key");String openid = (String) object.get("openid");HashMap<String, String> res = new HashMap<>();res.put("openid", openid);res.put("session_key", session_key);return res;}public static HashMap<String, String> get(String code) throws IOException {return get(appid, secret, code);}
}
4、编写控制器
@PostMapping("login")
public AjaxResult login(@RequestBody HashMap<String, String> code) throws IOException {HashMap<String, String> map = WxHttpClient.get(code.get("code"));System.out.println(map);return AjaxResult.success();}
打印结果格式如下:
{openid=odfCW5Kz3SfxpydxJH7dIHiCUwSo, session_key=FvEoC08amf16G0texJaBcA==}
可以通过get(key)
的方式取到值,具体如下:
String openid = map.get("openid");
String session_key = map.get("session_key");System.out.println("openid: "+openid);
System.out.println("session_key: "+session_key);
结果:
openid: odfCW5Kz3SfxpydxJH7dIHiCUwSo
session_key: 9reHgOu+urg1W1tWI32GVA==