时间:2020-01-01 09:14:29 | 栏目: | 点击:次
package com.wlw.util;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
/**
*
* 工具类
* 用来根据接口地址进行网络请求
* @author wlw
*
*/
public class AuthUtil {
public static final String APP_ID = "****************"; //填写自己的APPID
public static final String APP_SECRET = "**************"; //填写自己的APPSECRET
public static JSONObject doGetJson(String url) throws Exception, IOException {
JSONObject jsonObject=null;
//初始化httpClient
DefaultHttpClient client=new DefaultHttpClient();
//用Get方式进行提交
HttpGet httpGet=new HttpGet(url);
//发送请求
HttpResponse response= client.execute(httpGet);
//获取数据
HttpEntity entity=response.getEntity();
//格式转换
if (entity!=null) {
String result=EntityUtils.toString(entity,"UTF-8");
jsonObject=JSONObject.fromObject(result);
}
//释放链接
httpGet.releaseConnection();
return jsonObject;
}
}
package com.wlw.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wlw.util.AuthUtil;
import net.sf.json.JSONObject;
/**
* 回调地址
*
* @author wlw
*
*/
@WebServlet("/redirect_uri")
public class CallBackServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* 获取code
*/
String code=req.getParameter("code");
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APP_ID
+ "&secret="+AuthUtil.APP_SECRET
+ "&code="+code
+ "&grant_type=authorization_code";
JSONObject jsonObject;
try {
jsonObject = AuthUtil.doGetJson(url);
String openid=jsonObject.getString("openid");
String token=jsonObject.getString("access_token");
/**
* 拉取用户信息
*/
String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+token
+ "&openid="+openid
+ "&lang=zh_CN";
JSONObject userInfo=AuthUtil.doGetJson(infoUrl);//这里的userInfo已经是用户的信息了
System.out.println(userInfo);
//使用微信用户信息直接登录,无需注册和绑定
req.setAttribute("info", userInfo);
req.getRequestDispatcher("/index1.jsp").forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}