首页 > 代码库 > 微信支付后台获取openid

微信支付后台获取openid

@RequestMapping(value = "http://www.mamicode.com/postOpenid", method = RequestMethod.POST)
@ResponseBody
public String getOpenid(@RequestParam(value = "http://www.mamicode.com/code", required = false) String code, HttpServletRequest request,
ModelMap model) throws IOException {
System.out.println("code:" + code);
String openid = "";
List<Object> list = accessToken(code);
if (list.size() != 0) {
openid = list.get(0).toString();
}

return openid;

}

 

public List<Object> accessToken(String code) throws IOException {
List<Object> list = new ArrayList<Object>();
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + "   " + "&secret="
+ "   " + "&code=" + code + "&grant_type=authorization_code";
GetMethod get = null;
get = new GetMethod(url);

HttpClient client = new HttpClient();
client.getParams().setParameter("http.protocol.content-charset", "utf-8");
client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
client.getHttpConnectionManager().getParams().setSoTimeout(30000);

get.addRequestHeader("Content-type", "te|xt/html;charset=UTF-8");

int statusCode = 0;
try {
statusCode = client.executeMethod(get);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

if (statusCode == 200) {
InputStream resInputStream = null;
try {
resInputStream = get.getResponseBodyAsStream();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(resInputStream, "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line:" + line);
JSONObject jsonObject = new JSONObject();
try {
jsonObject = JSONObject.fromObject(line);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
System.out.println("openid:" + openid);
list.add(openid);
list.add(access_token);
} catch (Exception e) {
jsonObject = JSONObject.fromObject(line);
String errcode = jsonObject.getString("errcode");
System.out.println("errcode:" + errcode);
}
}
}
return list;

}

微信支付后台获取openid