java 小程序登陆_java 微信小程序登录

//前端传给你的code

public voidwxlogin(String code) {//填写你小程序的appid 和 secret , 还有前端传给你的code ,最后一个参数是固定的

String token_url= "https://api.weixin.qq.com/sns/jscode2session?appid=" +WxConfig.APP_ID + "&secret=" + WxConfig.SECRET + "&js_code=" + code + "&grant_type=authorization_code";

JSONObject access_token= httpsRequestToJsonObject(token_url, "GET", null);//openid string 用户唯一标识 这个就是你微信用户标识

String openid = access_token.getString("openid");//session_key string 会话密钥

String session_key = access_token.getString("session_key");//errcode number 错误码

String errcode = access_token.getString("errcode");//errmsg string 错误信息

String errmsg = access_token.getString("errmsg");if ("-1".equals(errcode)) {

System.err.println(errmsg);return;

}if ("4029".equals(errcode)) {

System.err.println(errmsg);return;

}if ("45011".equals(errcode)) {

System.err.println(errmsg);return;

}else{//证明没问题//保存openid 到你的数据库, 调用你的service 业务

}

}public staticJSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {

JSONObject jsonObject= null;try{

StringBuffer buffer=httpsRequest(requestUrl, requestMethod, outputStr);

jsonObject=JSONObject.fromObject(buffer.toString());

}catch(ConnectException ce) {

System.err.println("请求连接超时"+ce);

}catch(Exception e) {

System.err.println("https请求异常:" +e.getMessage());

}returnjsonObject;

}private staticStringBuffer httpsRequest(String requestUrl, String requestMethod, String output)throwsNoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,

IOException, ProtocolException, UnsupportedEncodingException {

URL url= new URL(null, requestUrl, newHandler());

HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();

connection.setDoOutput(true);

connection.setDoInput(true);

connection.setUseCaches(false);

connection.setRequestMethod(requestMethod);if (null !=output) {

OutputStream outputStream=connection.getOutputStream();

outputStream.write(output.getBytes("UTF-8"));

outputStream.close();

}//从输入流读取返回内容

InputStream inputStream =connection.getInputStream();

InputStreamReader inputStreamReader= new InputStreamReader(inputStream, "utf-8");

BufferedReader bufferedReader= newBufferedReader(inputStreamReader);

String str= null;

StringBuffer buffer= newStringBuffer();while ((str = bufferedReader.readLine()) != null) {

buffer.append(str);

}

bufferedReader.close();

inputStreamReader.close();

inputStream.close();

inputStream= null;

connection.disconnect();returnbuffer;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值