废话不多说直接上代码。
这里是获取微信openid的,只需要前台调用定义好的接口,就会把openid返回给前台。或者自行保存。
package com.ckugua.mentality.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.poi.util.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ckugua.mentality.util.JsonUtil;
//获取openid
@Controller
@RequestMapping("/wx/user")
public class UserController {
@ResponseBody
@RequestMapping("/huoquOpenid")
public String getUserInfo(@RequestParam(name= "code")String code) throws Exception {
Map<String,Object> rtnMap = new HashMap<String,Object>();
String url = "https://api.weixin.qq.com/sns/jscode2session";
url += "?appid=";//自己的appid
url += "&secret=";//密匙
url += "&js_code=" + code;
url += "&grant_type=authorization_code";
byte[] res = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
res = IOUtils.toByteArray(response.getEntity().getContent());
} catch (Exception e) {
throw e;
} finally {
if (httpget != null) {
httpget.abort();
}
httpclient.getConnectionManager().shutdown();
}
JSONObject jo = JSON.parseObject(new String(res, "utf-8"));
String openid = jo.getString("openid");
return openid;
}
}