找回密码
 立即注册
查看: 84|回复: 0

HttpClient,httpclient在springboot3微信登录实操案例代码

[复制链接]

156

主题

5

精华

160

金币

技术维护QQ:515138

积分
345
发表于 2025-12-23 14:15:23 | 显示全部楼层 |阅读模式
HttpClient,httpclient在springboot3微信登录实操案例代码

实现层:
  1. package com.zidiu.service.impl;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.zidiu.constant.MessageConstant;
  5. import com.zidiu.dto.UserLoginDTO;
  6. import com.zidiu.entity.User;
  7. import com.zidiu.exception.LoginFailedException;
  8. import com.zidiu.mapper.UserMapper;
  9. import com.zidiu.properties.WeChatProperties;
  10. import com.zidiu.service.UserService;
  11. import com.zidiu.utils.HttpClientUtil;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.stereotype.Service;
  15. import java.time.LocalDateTime;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. @Service
  19. @Slf4j
  20. public class UserServiceImpl implements UserService {
  21.     //微信服务接口地址
  22.     private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
  23.     @Autowired
  24.     private WeChatProperties weChatProperties;
  25.     @Autowired
  26.     private UserMapper userMapper;
  27.     /**
  28.      * 微信登录
  29.      * @param userLoginDTO
  30.      * @return
  31.      */
  32.     public User wxLogin(UserLoginDTO userLoginDTO) {
  33.         String openid = getOpenid(userLoginDTO.getCode());
  34.         //判断openid是否为空,如果为空表示登录失败,抛出业务异常
  35.         if(openid == null){
  36.             throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
  37.         }
  38.         //判断当前用户是否为新用户
  39.         User user = userMapper.getByOpenid(openid);
  40.         //如果是新用户,自动完成注册
  41.         if(user == null){
  42.             user = User.builder()
  43.                     .openid(openid)
  44.                     .createTime(LocalDateTime.now())
  45.                     .build();
  46.             userMapper.insert(user);
  47.         }
  48.         //返回这个用户对象
  49.         return user;
  50.     }
  51.     /**
  52.      * 调用微信接口服务,获取微信用户的openid
  53.      * @param code
  54.      * @return
  55.      */
  56.     private String getOpenid(String code){
  57.         //调用微信接口服务,获得当前微信用户的openid
  58.         Map<String, String> map = new HashMap<>();
  59.         map.put("appid",weChatProperties.getAppid());
  60.         map.put("secret",weChatProperties.getSecret());
  61.         map.put("js_code",code);
  62.         map.put("grant_type","authorization_code");
  63.         String json = HttpClientUtil.doGet(WX_LOGIN, map);
  64.         JSONObject jsonObject = JSON.parseObject(json);
  65.         String openid = jsonObject.getString("openid");
  66.         return openid;
  67.     }
  68. }
复制代码
HttpClient封装工具:

  1. package com.zidiu.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.http.NameValuePair;
  4. import org.apache.http.client.config.RequestConfig;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.client.utils.URIBuilder;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.HttpClients;
  13. import org.apache.http.message.BasicNameValuePair;
  14. import org.apache.http.util.EntityUtils;
  15. import java.io.IOException;
  16. import java.net.URI;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import java.util.Map;
  20. /**
  21. * Http工具类
  22. */
  23. public class HttpClientUtil {
  24.     static final  int TIMEOUT_MSEC = 5 * 1000;
  25.     /**
  26.      * 发送GET方式请求
  27.      * @param url
  28.      * @param paramMap
  29.      * @return
  30.      */
  31.     public static String doGet(String url,Map<String,String> paramMap){
  32.         // 创建Httpclient对象
  33.         CloseableHttpClient httpClient = HttpClients.createDefault();
  34.         String result = "";
  35.         CloseableHttpResponse response = null;
  36.         try{
  37.             URIBuilder builder = new URIBuilder(url);
  38.             if(paramMap != null){
  39.                 for (String key : paramMap.keySet()) {
  40.                     builder.addParameter(key,paramMap.get(key));
  41.                 }
  42.             }
  43.             URI uri = builder.build();
  44.             //创建GET请求
  45.             HttpGet httpGet = new HttpGet(uri);
  46.             //发送请求
  47.             response = httpClient.execute(httpGet);
  48.             //判断响应状态
  49.             if(response.getStatusLine().getStatusCode() == 200){
  50.                 result = EntityUtils.toString(response.getEntity(),"UTF-8");
  51.             }
  52.         }catch (Exception e){
  53.             e.printStackTrace();
  54.         }finally {
  55.             try {
  56.                 response.close();
  57.                 httpClient.close();
  58.             } catch (IOException e) {
  59.                 e.printStackTrace();
  60.             }
  61.         }
  62.         return result;
  63.     }
  64.     /**
  65.      * 发送POST方式请求
  66.      * @param url
  67.      * @param paramMap
  68.      * @return
  69.      * @throws IOException
  70.      */
  71.     public static String doPost(String url, Map<String, String> paramMap) throws IOException {
  72.         // 创建Httpclient对象
  73.         CloseableHttpClient httpClient = HttpClients.createDefault();
  74.         CloseableHttpResponse response = null;
  75.         String resultString = "";
  76.         try {
  77.             // 创建Http Post请求
  78.             HttpPost httpPost = new HttpPost(url);
  79.             // 创建参数列表
  80.             if (paramMap != null) {
  81.                 List<NameValuePair> paramList = new ArrayList();
  82.                 for (Map.Entry<String, String> param : paramMap.entrySet()) {
  83.                     paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
  84.                 }
  85.                 // 模拟表单
  86.                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
  87.                 httpPost.setEntity(entity);
  88.             }
  89.             httpPost.setConfig(builderRequestConfig());
  90.             // 执行http请求
  91.             response = httpClient.execute(httpPost);
  92.             resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
  93.         } catch (Exception e) {
  94.             throw e;
  95.         } finally {
  96.             try {
  97.                 response.close();
  98.             } catch (IOException e) {
  99.                 e.printStackTrace();
  100.             }
  101.         }
  102.         return resultString;
  103.     }
  104.     /**
  105.      * 发送POST方式请求
  106.      * @param url
  107.      * @param paramMap
  108.      * @return
  109.      * @throws IOException
  110.      */
  111.     public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
  112.         // 创建Httpclient对象
  113.         CloseableHttpClient httpClient = HttpClients.createDefault();
  114.         CloseableHttpResponse response = null;
  115.         String resultString = "";
  116.         try {
  117.             // 创建Http Post请求
  118.             HttpPost httpPost = new HttpPost(url);
  119.             if (paramMap != null) {
  120.                 //构造json格式数据
  121.                 JSONObject jsonObject = new JSONObject();
  122.                 for (Map.Entry<String, String> param : paramMap.entrySet()) {
  123.                     jsonObject.put(param.getKey(),param.getValue());
  124.                 }
  125.                 StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
  126.                 //设置请求编码
  127.                 entity.setContentEncoding("utf-8");
  128.                 //设置数据类型
  129.                 entity.setContentType("application/json");
  130.                 httpPost.setEntity(entity);
  131.             }
  132.             httpPost.setConfig(builderRequestConfig());
  133.             // 执行http请求
  134.             response = httpClient.execute(httpPost);
  135.             resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
  136.         } catch (Exception e) {
  137.             throw e;
  138.         } finally {
  139.             try {
  140.                 response.close();
  141.             } catch (IOException e) {
  142.                 e.printStackTrace();
  143.             }
  144.         }
  145.         return resultString;
  146.     }
  147.     private static RequestConfig builderRequestConfig() {
  148.         return RequestConfig.custom()
  149.                 .setConnectTimeout(TIMEOUT_MSEC)
  150.                 .setConnectionRequestTimeout(TIMEOUT_MSEC)
  151.                 .setSocketTimeout(TIMEOUT_MSEC).build();
  152.     }
  153. }
复制代码
jinhei-waimai.zip (526.02 KB, 下载次数: 0, 售价: 50 金币)



上一篇:springboot3缓存redis菜品处理代码
下一篇:Spring Cache缓存机制案例
网站建设,公众号小程序开发,系统定制,软件App开发,技术维护【联系我们】手机/微信:17817817816 QQ:515138

QQ|Archiver|自丢网 ( 粤ICP备2024252464号-1 )

GMT+8, 2026-1-19 13:44

专注于网站建设,公众号小程序制作,商城小程序,系统定制,软件App开发

【联系我们】手机/微信:17817817816 QQ:515138

快速回复 返回顶部 返回列表