最最最详细的springboot项目中集成微信扫码登入功能.步骤代码超级详细(OAuth2)

2023-10-27

说到登录注册,就会想到先要注册一个用户名,在进行登入,但是现在大多数的网站都集成了微信登入,不需要注册,给你一个二维码,微信一扫直接登录.这确实是十分便捷的.所以我们会尽量在项目中实现这一功能.减少用户操作,提高用户产品体验.

由于微信是腾讯所有,所以要集成微信,就需要按照腾讯设定的规则来进行.
前提我们来讲一个理论上的东西叫OAuth2
理论部分
OAuth2是什么?
1.OAuth2是针对特定问题的一种解决方案
- OAuth2主要解决两个问题

(1)开放系统间的授权

照片拥有者想要在云冲印服务上打印照片,云冲印服务需要访问云存储服务上的资源

在这里插入图片描述举例:假如说有一个人有一张照片,存储在了百度网盘上,市场上有一个服务,打印存的这张照片,现在就是人可以操作百度网盘,但是打印服务不能访问别人的网盘,这个时候人就需要用一个工具给这个服务授权操作自己的百度云盘.

授权方案:
1.用户名密码复制
  这个人直接将自己的百度云盘密码给到这个工具,工具操作打印服务,对云云盘中的照片进行打印(安全性太差)
在这里插入图片描述

2.通用的开发者key
  适用于合作商或者授信的不同业务部门之间
一般使用与关系对等的情况下
  用一个万能钥匙,进行授权
在这里插入图片描述3.办法令牌
  接近OAuth2方式,需要考虑如何管理令牌、颁发令牌、吊销令牌,需要统一的协议,因此就有了OAuth2协议

在这里插入图片描述类似token.

(2)分布式访问(单点登录)

假如说有一个分布式项目,有三个模块.在一个模块登录后,其他模块都能访问,都已经登录了.

1.登录成功后,按照一定规则生成字符串,字符串包含用户信息
2.把生成的字符串通过路径传播,或者cookie
3.后面再发送请求的时候,每次呆着字符串进行发送,获取字符串,从字符串和获取用户信息登录.

这样就是OAuth2解决方案:令牌机制.

这里有一个误区需要我们注意:
在这里插入图片描述关于auth2的更多信息在这里不做详细说明
转回我们的主题,微信登录.
微信扫描登录准备
准备过程:
第一步:注册开发者资质
链接: https://open.weixin.qq.com/

在这里插入图片描述目前来说只能支持企业的资质认证,个人的暂且不支持.
注册之后,提供微信id和微信密钥.
详细步骤:
https://open.weixin.qq.com
1、注册
2、邮箱激活
3、完善开发者资料
4、开发者资质认证
准备营业执照,1-2个工作日审批、300元
5、创建网站应用
提交审核,7个工作日审批
6、熟悉微信登录流程
参考文档:
链接: 文档连接.
获取access_token时序图
在这里插入图片描述前面的步骤主要是为了拿到微信给的授权id和密钥
后端开发步骤:
1.配置文件application.properties

# 微信开放平台 appid
wx.open.app_id=你的appid
# 微信开放平台 appsecret
wx.open.app_secret=你的appsecret
# 微信开放平台 重定向url
wx.open.redirect_url=http://你的服务器名称/api/ucenter/wx/callback

2.创建一个工具类读取文件

package com.qiu.educenter.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantWxUtils implements InitializingBean {
    @Value("${wx.open.app_id}")
    private String appId;

    @Value("${wx.open.app_secret}")
    private String appSecret;

    @Value("${wx.open.redirect_url}")
    private String redirectUrl;

    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;
    public static String WX_OPEN_REDIRECT_URL;
    @Override
    public void afterPropertiesSet() throws Exception {
        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
    }
}

3.生成一个微信扫描的二维码
在这里插入图片描述这里微信给了一个固定的地址

官方文档
i.请求code
第三方使用网站应用授权登录前请注意已获取相应网页授权作用域 (scope=snsapi_login),则可以通过在PC端打开以下链接: https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 若提示“该链接无法访问”,请检查参数是否填写错误,如redirect_uri的域名与审核时填写的授权域名不一致或scope不为snsapi_login。`

参数说明

参数 是否必须 说明
appid 应用唯一标识
redirect_uri 请使用urlEncode对链接进行处理
response_type 填code
scope 应用授权作用域,拥有多个作用域用逗号(,)分隔,网页应用目前仅填写snsapi_login
state 用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验

做法
直接请求微信提供固定的地址,向地址后面拼接参数
项目中新建一个controller

package com.qiu.educenter.controller;

import com.qiu.educenter.utils.ConstantWxUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @GetMapping("callback")
    //这种规则只是为了测试,在实际开发中并不需要这么做
    public String callback(String code,String state){
        System.out.println(code);
        return "redirect:http://localhost:3000";
    }
    //1.生成微信扫描二维码
    @GetMapping("login") //直接生成二维码,不返回数据
    public String getWxCode(){
        /*第一种方式:固定地址后面拼参数,参数太多,容易拼错
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID
            +"&response_type=code";
         */
        //第二种方式:%s:相当于一个占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEnccode编码
        String redirect_url =ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirect_url = URLEncoder.encode(redirect_url, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url =String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                redirect_url,
                "qiuzhikang"
        );
        //请求微信地址
        return "redirect:"+url;
    }
}

扫描之后,执行了本地的callback方法.在calllback方法中获取到了两个值,在跳转的时候传来的.
第一步:

1.code:类似于手机验证码1,随机唯一的值
2.state:原样传递

第二步:拿着第一步获取到的code值请求微信提供固定的地址.可以获取到两个值,一个是accessToken另一个是openid.

1.accessToken:访问凭证
2.openid:区分不同微信的唯一标识

第三步:拿着第二步获取到的两个值access_token,openid再去请求微信给出的一个固定地址.最终才可以获取到微信扫码人的信息,比如说微信扫码人的昵称,头像等等.

多步骤也是为了从安全考虑.
我们再来看看这张时序图:

在这里插入图片描述这个时候就能看明白很多了

这里用到了几个技术点:
httpclient:这个能做到不需要浏览器也能做到浏览器的效果
json转换工具:gson,jackjson等等

完整的controller:

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;
    @GetMapping("callback")
    //这种规则只是为了测试,在实际开发中并不需要这么做
    public String callback(String code,String state){
        try{
//1.获取code值,临时票据,类似于验证码
            System.out.println(code);

            //2.拿着code请求微信固定的地址,得到两个值access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //请求这个拼接好的地址得到返回的值,现在请求地址,不用浏览器了,用httpclient发送一个请求得到一个返回的地址
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);//得到的是一个json的字符串,并不是前端需要的json数据
            //所以我们需要对字符串进行分割,先将字符串转换成map集合,map是key-value结构,再根据map中的key得到结果,这里我们用gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);//将字符串转换成Hashmao
            String access_token =(String) mapAccessToken.get("access_token");
            String openid = (String)mapAccessToken.get("openid");

            //扫码人信息加到数据库中去
            //判断数据库中是否存在相同的数据库信息,我们可以根据openid来做判断
            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member ==null){
                //member为空,表示数据库中没有相同的信息
                //3.拿到access_token和openid,再去请求微信提供固定的地址,获取到扫码人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //获取返回的userInfo字符串的扫描人信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname =(String) userInfoMap.get("nickname");//昵称
                String headimgurl =(String) userInfoMap.get("headimgurl");//头像

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            //最后返回我们的首页面
            //由于我们在前端中需要显示用户名和头像,所以我们需要使用jwt在地址中传递token
            //不能使用cookie,是因为cookie不能跨域访问,会导致值传递失败
            //使用jwt根据member对象生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            
            return "redirect:http://localhost:3000?token="+jwtToken;
        }catch(Exception e){
           throw new QiuException(20001,"登录失败");
        }
    }
    //1.生成微信扫描二维码
    @GetMapping("login") //直接生成二维码,不返回数据
    public String getWxCode(){
        /*第一种方式:固定地址后面拼参数,参数太多,容易拼错
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID
            +"&response_type=code";
         */
        //第二种方式:%s:相当于一个占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEnccode编码
        String redirect_url =ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirect_url = URLEncoder.encode(redirect_url, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url =String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                redirect_url,
                "atguigu"
        );
        //请求微信地址
        return "redirect:"+url;
    }
}


service层:

/**
 * <p>
 * 会员表 服务类
 * </p>
 *
 * @author qiuzhikang
 * @since 2020-08-15
 */
public interface UcenterMemberService extends IService<UcenterMember> {

    String login(UcenterMember member);

    void register(RegisterVo registerVo);


    UcenterMember getOpenIdMember(String openid);
}

impl:

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author qiuzhikang
 * @since 2020-08-15
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public String login(UcenterMember member) {

        //原始方法就是用UcenterMember里面的用户名密码在数据库中做比对
        //现在用一种新的方式

        //获取手机号和密码
        String mobile = member.getMobile();
        String password = member.getPassword();
        //手机号和密码飞空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new QiuException(20001,"用户名密码不为空,登录失败");
        }
        //判断手机号是否正确
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        UcenterMember mobileMember = baseMapper.selectOne(wrapper);
        //判断查出来对象是否为空
        if (mobileMember == null){
            //没有这个手机号
            throw new QiuException(20001,"登录失败");
        }
        //判断密码是否正确
        if (!MD5.encrypt(password).equals(mobileMember.getPassword())){
            //密码不一样
            throw new QiuException(20001,"登录失败");
        }
        if (mobileMember.getIsDisabled()){
            //账号是否被禁用
            throw new QiuException(20001,"登录失败");
        }

        //表示登录成功了
        //生成token的字符串,使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(mobileMember.getId(),mobileMember.getNickname());
        System.out.println(member.getId()+member.getNickname());
        return jwtToken;
    }
//注册的方法
    @Override
    public void register(RegisterVo registerVo) {
        //获取注册的数据
        String code = registerVo.getCode();

        String mobile = registerVo.getMobile();

        String nickname = registerVo.getNickname();

        String password = registerVo.getPassword();
        //非空判断
        if (StringUtils.isEmpty(code) ||StringUtils.isEmpty(mobile)
                ||StringUtils.isEmpty(nickname) ||StringUtils.isEmpty(password) ){
            throw new QiuException(20001,"注册失败,数据不能为空");
        }

        //判断验证码,与redis中存的验证码是否一样
        String redisCode = redisTemplate.opsForValue().get(mobile);
        System.out.println(redisCode);
        if (!code.equals(redisCode)){
            throw new QiuException(20001,"验证码输入不一致");
        }
        //判断手机号是否重复
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0){
            throw new QiuException(20001,"手机号已被使用");
        }
        //数据添加到数据库中
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setMobile(mobile);
        ucenterMember.setPassword(MD5.encrypt(password));
        ucenterMember.setNickname(nickname);
        ucenterMember.setIsDisabled(false);
        ucenterMember.setAvatar("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597470759261&di=92492bc30e5e16276723561870a3ed60&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201505%2F04%2F20150504013225_XZNCu.thumb.700_0.jpeg");
        baseMapper.insert(ucenterMember);

    }

    @Override
    public UcenterMember getOpenIdMember(String openid) {
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UcenterMember member = baseMapper.selectOne(wrapper);


        return member;
    }
}

这里面需要使用到的两个工具类:
jwtUtils:

public class JwtUtils {

    public static final long EXPIRE = 1000 * 60 * 60 * 24;//设置token过期时间的值
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";//密钥,为了后面做加密的编码,这个密码是随便写的

    public static String getJwtToken(String id, String nickname){
        //构建JWT字符串,设置头部的信息,也就是JWT三部分中的第一部分
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置过期时间
                .setSubject("guli-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token的主题部分
                .claim("id", id)
                .claim("nickname", nickname)
                //签名哈希,
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员id
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();//得到字符串的主题部分
        return (String)claims.get("id");
    }
}

httpclient:

/**
 *  依赖的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar
 * @author zhaoyb
 *
 */
public class HttpClientUtils {

	public static final int connTimeout=10000;
	public static final int readTimeout=10000;
	public static final String charset="UTF-8";
	private static HttpClient client = null;

	static {
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(128);
		cm.setDefaultMaxPerRoute(128);
		client = HttpClients.custom().setConnectionManager(cm).build();
	}

	public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
		return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
	}

	public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
		return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
	}

	public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
			SocketTimeoutException, Exception {
		return postForm(url, params, null, connTimeout, readTimeout);
	}

	public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
			SocketTimeoutException, Exception {
		return postForm(url, params, null, connTimeout, readTimeout);
	}

	public static String get(String url) throws Exception {
		return get(url, charset, null, null);
	}

	public static String get(String url, String charset) throws Exception {
		return get(url, charset, connTimeout, readTimeout);
	}

	/**
	 * 发送一个 Post 请求, 使用指定的字符集编码.
	 *
	 * @param url
	 * @param body RequestBody
	 * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
	 * @param charset 编码
	 * @param connTimeout 建立链接超时时间,毫秒.
	 * @param readTimeout 响应超时时间,毫秒.
	 * @return ResponseBody, 使用指定的字符集编码.
	 * @throws ConnectTimeoutException 建立链接超时异常
	 * @throws SocketTimeoutException  响应超时
	 * @throws Exception
	 */
	public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
			throws ConnectTimeoutException, SocketTimeoutException, Exception {
		HttpClient client = null;
		HttpPost post = new HttpPost(url);
		String result = "";
		try {
			if (StringUtils.isNotBlank(body)) {
				HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
				post.setEntity(entity);
			}
			// 设置参数
			Builder customReqConf = RequestConfig.custom();
			if (connTimeout != null) {
				customReqConf.setConnectTimeout(connTimeout);
			}
			if (readTimeout != null) {
				customReqConf.setSocketTimeout(readTimeout);
			}
			post.setConfig(customReqConf.build());

			HttpResponse res;
			if (url.startsWith("https")) {
				// 执行 Https 请求.
				client = createSSLInsecureClient();
				res = client.execute(post);
			} else {
				// 执行 Http 请求.
				client = HttpClientUtils.client;
				res = client.execute(post);
			}
			result = IOUtils.toString(res.getEntity().getContent(), charset);
		} finally {
			post.releaseConnection();
			if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
				((CloseableHttpClient) client).close();
			}
		}
		return result;
	}


	/**
	 * 提交form表单
	 *
	 * @param url
	 * @param params
	 * @param connTimeout
	 * @param readTimeout
	 * @return
	 * @throws ConnectTimeoutException
	 * @throws SocketTimeoutException
	 * @throws Exception
	 */
	public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
			SocketTimeoutException, Exception {

		HttpClient client = null;
		HttpPost post = new HttpPost(url);
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> formParams = new ArrayList<NameValuePair>();
				Set<Entry<String, String>> entrySet = params.entrySet();
				for (Entry<String, String> entry : entrySet) {
					formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
				post.setEntity(entity);
			}

			if (headers != null && !headers.isEmpty()) {
				for (Entry<String, String> entry : headers.entrySet()) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}
			// 设置参数
			Builder customReqConf = RequestConfig.custom();
			if (connTimeout != null) {
				customReqConf.setConnectTimeout(connTimeout);
			}
			if (readTimeout != null) {
				customReqConf.setSocketTimeout(readTimeout);
			}
			post.setConfig(customReqConf.build());
			HttpResponse res = null;
			if (url.startsWith("https")) {
				// 执行 Https 请求.
				client = createSSLInsecureClient();
				res = client.execute(post);
			} else {
				// 执行 Http 请求.
				client = HttpClientUtils.client;
				res = client.execute(post);
			}
			return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
		} finally {
			post.releaseConnection();
			if (url.startsWith("https") && client != null
					&& client instanceof CloseableHttpClient) {
				((CloseableHttpClient) client).close();
			}
		}
	}




	/**
	 * 发送一个 GET 请求
	 *
	 * @param url
	 * @param charset
	 * @param connTimeout  建立链接超时时间,毫秒.
	 * @param readTimeout  响应超时时间,毫秒.
	 * @return
	 * @throws ConnectTimeoutException   建立链接超时
	 * @throws SocketTimeoutException   响应超时
	 * @throws Exception
	 */
	public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
			throws ConnectTimeoutException,SocketTimeoutException, Exception {

		HttpClient client = null;
		HttpGet get = new HttpGet(url);
		String result = "";
		try {
			// 设置参数
			Builder customReqConf = RequestConfig.custom();
			if (connTimeout != null) {
				customReqConf.setConnectTimeout(connTimeout);
			}
			if (readTimeout != null) {
				customReqConf.setSocketTimeout(readTimeout);
			}
			get.setConfig(customReqConf.build());

			HttpResponse res = null;

			if (url.startsWith("https")) {
				// 执行 Https 请求.
				client = createSSLInsecureClient();
				res = client.execute(get);
			} else {
				// 执行 Http 请求.
				client = HttpClientUtils.client;
				res = client.execute(get);
			}

			result = IOUtils.toString(res.getEntity().getContent(), charset);
		} finally {
			get.releaseConnection();
			if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
				((CloseableHttpClient) client).close();
			}
		}
		return result;
	}


	/**
	 * 从 response 里获取 charset
	 *
	 * @param ressponse
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String getCharsetFromResponse(HttpResponse ressponse) {
		// Content-Type:text/html; charset=GBK
		if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
			String contentType = ressponse.getEntity().getContentType().getValue();
			if (contentType.contains("charset=")) {
				return contentType.substring(contentType.indexOf("charset=") + 8);
			}
		}
		return null;
	}



	/**
	 * 创建 SSL连接
	 * @return
	 * @throws GeneralSecurityException
	 */
	private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
					return true;
				}
			}).build();

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}

				@Override
				public void verify(String host, SSLSocket ssl)
						throws IOException {
				}

				@Override
				public void verify(String host, X509Certificate cert)
						throws SSLException {
				}

				@Override
				public void verify(String host, String[] cns,
								   String[] subjectAlts) throws SSLException {
				}

			});

			return HttpClients.custom().setSSLSocketFactory(sslsf).build();

		} catch (GeneralSecurityException e) {
			throw e;
		}
	}

	public static void main(String[] args) {
		try {
			String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
			//String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");
            /*Map<String,String> map = new HashMap<String,String>();
            map.put("name", "111");
            map.put("page", "222");
            String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/
			System.out.println(str);
		} catch (ConnectTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

最最最详细的springboot项目中集成微信扫码登入功能.步骤代码超级详细(OAuth2) 的相关文章

随机推荐