HttpClient,httpclient在springboot3微信登录实操案例代码
实现层:
- package com.zidiu.service.impl;
-
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.zidiu.constant.MessageConstant;
- import com.zidiu.dto.UserLoginDTO;
- import com.zidiu.entity.User;
- import com.zidiu.exception.LoginFailedException;
- import com.zidiu.mapper.UserMapper;
- import com.zidiu.properties.WeChatProperties;
- import com.zidiu.service.UserService;
- import com.zidiu.utils.HttpClientUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.time.LocalDateTime;
- import java.util.HashMap;
- import java.util.Map;
-
- @Service
- @Slf4j
- public class UserServiceImpl implements UserService {
-
- //微信服务接口地址
- private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
-
- @Autowired
- private WeChatProperties weChatProperties;
- @Autowired
- private UserMapper userMapper;
-
- /**
- * 微信登录
- * @param userLoginDTO
- * @return
- */
- public User wxLogin(UserLoginDTO userLoginDTO) {
- String openid = getOpenid(userLoginDTO.getCode());
-
- //判断openid是否为空,如果为空表示登录失败,抛出业务异常
- 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;
- }
-
- /**
- * 调用微信接口服务,获取微信用户的openid
- * @param code
- * @return
- */
- 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;
- }
- }
复制代码 HttpClient封装工具:
- package com.zidiu.utils;
-
- import com.alibaba.fastjson.JSONObject;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.utils.URIBuilder;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
-
- import java.io.IOException;
- import java.net.URI;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- /**
- * Http工具类
- */
- public class HttpClientUtil {
-
- static final int TIMEOUT_MSEC = 5 * 1000;
-
- /**
- * 发送GET方式请求
- * @param url
- * @param paramMap
- * @return
- */
- public static String doGet(String url,Map<String,String> paramMap){
- // 创建Httpclient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
-
- String result = "";
- CloseableHttpResponse response = null;
-
- try{
- URIBuilder builder = new URIBuilder(url);
- if(paramMap != null){
- for (String key : paramMap.keySet()) {
- builder.addParameter(key,paramMap.get(key));
- }
- }
- URI uri = builder.build();
-
- //创建GET请求
- HttpGet httpGet = new HttpGet(uri);
-
- //发送请求
- response = httpClient.execute(httpGet);
-
- //判断响应状态
- if(response.getStatusLine().getStatusCode() == 200){
- result = EntityUtils.toString(response.getEntity(),"UTF-8");
- }
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- try {
- response.close();
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- return result;
- }
-
- /**
- * 发送POST方式请求
- * @param url
- * @param paramMap
- * @return
- * @throws IOException
- */
- public static String doPost(String url, Map<String, String> paramMap) throws IOException {
- // 创建Httpclient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- String resultString = "";
-
- try {
- // 创建Http Post请求
- HttpPost httpPost = new HttpPost(url);
-
- // 创建参数列表
- if (paramMap != null) {
- List<NameValuePair> paramList = new ArrayList();
- for (Map.Entry<String, String> param : paramMap.entrySet()) {
- paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
- }
- // 模拟表单
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
- httpPost.setEntity(entity);
- }
-
- httpPost.setConfig(builderRequestConfig());
-
- // 执行http请求
- response = httpClient.execute(httpPost);
-
- resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
- } catch (Exception e) {
- throw e;
- } finally {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- return resultString;
- }
-
- /**
- * 发送POST方式请求
- * @param url
- * @param paramMap
- * @return
- * @throws IOException
- */
- public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
- // 创建Httpclient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- String resultString = "";
-
- try {
- // 创建Http Post请求
- HttpPost httpPost = new HttpPost(url);
-
- if (paramMap != null) {
- //构造json格式数据
- JSONObject jsonObject = new JSONObject();
- for (Map.Entry<String, String> param : paramMap.entrySet()) {
- jsonObject.put(param.getKey(),param.getValue());
- }
- StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
- //设置请求编码
- entity.setContentEncoding("utf-8");
- //设置数据类型
- entity.setContentType("application/json");
- httpPost.setEntity(entity);
- }
-
- httpPost.setConfig(builderRequestConfig());
-
- // 执行http请求
- response = httpClient.execute(httpPost);
-
- resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
- } catch (Exception e) {
- throw e;
- } finally {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- return resultString;
- }
- private static RequestConfig builderRequestConfig() {
- return RequestConfig.custom()
- .setConnectTimeout(TIMEOUT_MSEC)
- .setConnectionRequestTimeout(TIMEOUT_MSEC)
- .setSocketTimeout(TIMEOUT_MSEC).build();
- }
-
- }
复制代码
jinhei-waimai.zip
(526.02 KB, 下载次数: 0, 售价: 50 金币)
|