本文记录了苍穹外卖项目第六天的学习内容,重点介绍了微信小程序登录认证流程的实现以及HTTPClient在Web服务开发中的应用技术。

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
业务场景
在应用程序中访问如扫描支付、获取验证码、查看天气等服务,需要发送HTTP请求,并且接收响应数据,可通过HttpClient来实现。
核心API
HttpClient:Http客户端对象类型,使用该类型对象可发起Http请求。 HttpClients:可认为是构建器,可创建HttpClient对象。 CloseableHttpClient:实现类,实现了HttpClient接口。 HttpGet:Get方式请求类型。 HttpPost:Post方式请求类型。
实现流程
1.创建HttpClient对象 2.创建Http请求对象 3,调用HttpClient的execute方法发送请求
Get方式请求
@SpringBootTest
public class HttpClientTest {
/**
* 测试通过httpclient发送GET方式的请求
*/
@Test
public void testGET() throws Exception{
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求,接受响应结果
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码为:" + statusCode);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
System.out.println("服务端返回的数据为:" + body);
//关闭资源
response.close();
httpClient.close();
}
}POST方式请求
@Test
public void testPOST() throws Exception{
// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
StringEntity entity = new StringEntity(jsonObject.toString());
//指定请求编码方式
entity.setContentEncoding("utf-8");
//数据格式
entity.setContentType("application/json");
httpPost.setEntity(entity);
//发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//解析返回结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("响应码为:" + statusCode);
HttpEntity entity1 = response.getEntity();
String body = EntityUtils.toString(entity1);
System.out.println("响应数据为:" + body);
//关闭资源
response.close();
httpClient.close();
}
wx.login()获取临时登录凭证 code,调用wx.request()发送code授权码至开发者服务器session_key 和 openid,并生成自定义登录态(token)返回给小程序存储storage,并在后续业务请求中携带token便于身份校验Controller功能:
1.接收小程序端的请求,获得包含appid、appsecret和
code的UserLoginDTO对象 2.调用Service层的wxLogin方法,触发微信登录逻辑,获得包含openid参数的用户对象 3.以用户ID作为载荷,生成JWT令牌 4.构建UserLoginVO对象,包含ID、openid与token,通过Result.success返回小程序端
@RestController
@RequestMapping("/user/user")
@Api(tags="C端用户相关端口")
@Slf4j
public class UserController {
@Autowired
private JwtProperties jwtProperties;
@Autowired
private UserService userService;
@PostMapping("/login")
@ApiOperation("微信登陆")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
log.info("微信用户登录{}",userLoginDTO.getCode());
User user=userService.wxLogin(userLoginDTO);
//生成JWT令牌
Map<String, Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.USER_ID,user.getId());
String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
UserLoginVO userLoginVO = UserLoginVO.builder()
.id(user.getId())
.openid(user.getOpenid())
.token(token)
.build();
return Result.success(userLoginVO);
}
}Service层主要分为wxLogin与getOpenid方法构成
wxLogin方法功能:
1.调用getOpenid方法,获取
openid这个重要参数(用户唯一标识) 2.通过openid查询数据库,若用户不存在,则通过mapper层创建用户并返回对象
public User wxLogin(UserLoginDTO userLoginDTO) {
String openid = getOpenid(userLoginDTO.getCode());
if (openid==null){
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
User user=userMapper.getByOpenId(openid);
//用户是否新用户
if (user==null){
user = User.builder()
.openid(openid)
.createTime(LocalDateTime.now())
.build();
userMapper.insert(user);
}
return user;
}getOpenid方法功能:通过调用微信接口服务,获取openid并返回。
private String getOpenid(String code){
//调用微信接口服务,获得当前微信用户的openid
Map<String, String> map = new HashMap<>();
map.put("appid",weChatProperties.getAppid());
map.put("secret",weChatProperties.getSecret());
map.put("js_code",code);
map.put("grant_type","authorization_code");
String json = HttpClientUtil.doGet(WX_LOGIN, map);
JSONObject jsonObject = JSON.parseObject(json);
String openid = jsonObject.getString("openid");
return openid;
}session_key是微信小程序登录微信服务器返回的会话密钥,他主要作用于数据解密和签名验证,用于验证用户身份和数据完整性。
不使用session_key的原因
1.当前项目只需要用户身份识别 2.不需要解密用户数据 3.不需要验证数据签名 4.只需要
openid作为用户唯一标识
本文为苍穹外卖项目学习笔记,持续更新中…
如果我的内容对你有帮助,希望可以收获你的点赞、评论、收藏。