时间:2019-05-04 来源:小程序工厂
小***: package cn.allmy.ceiling.controller;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.qcloud.Utilities.Json.JSONObject;
public class UserController {
@RequestMapping("handle_userSeion")//此处填自己要用到的项目名。
@ResponseBody
public static void getOpenid(@RequestParam(value="code",required=false)String getcode) {//接收用户传过来的code,required=false表明如果这个参数没有传过来也可以。
// String code=getcode;
//接收从客户端获取的code
//向微信后台发起请求获取openid的url
String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
String requestUrl = WX_URL.replace("APPID", "------------------").//填写自己的appid
replace("SECRET", "----------------------").replace("JSCODE", code).//填写自己的appsecret,
replace("authorization_code", "authorization_code");
//调用get方法发起get请求,并把返回值赋值给returnvalue
String returnvalue=GET(requestUrl);
System.out.println(requestUrl);//打印发起请求的url
System.out.println(returnvalue);//打印调用GET方法返回值
//定义一个json对象。
JSONObject convertvalue=new JSONObject();
//将得到的字符串转换为json
convertvalue=(JSONObject) JSON.parse(returnvalue);
System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
//把openid和sessionkey分别赋值给openid和sessionkey
String openid=(String) convertvalue.get("openid");
String sessionkey=(String) convertvalue.get("session_key");//定义两个变量存储得到的openid和session_key.
}
public static String GET(String url) {
String result = "";
BufferedReader in = null;
InputStream is = null;
InputStreamReader isr = null;
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.connect();
Map
is = conn.getInputStream();
isr = new InputStreamReader(is);
in = new BufferedReader(isr);
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
// 异常记录
} finally {
try {
if (in != null) {
in.close();
}
if (is != null) {
is.close();
}
if (isr != null) {
isr.close();
}
} catch (Exception e2) {
// 异常记录
}
}
return result;
}
/*此方法没有用到。就先放在这吧
public static String jedisOperate(String Session_key, String openid) {
//这里需要引入一下jedis的dependenicy
Jedis jedis = new Jedis("localhost");
String openid = openid;