微信公众号网页授权思路解析及具体代码
实现方式也是两种:
1.静默授权登录 授权登录以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)特点:用户无感知;
非静默授权
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;
}
}
这里解释一下回调函数:回调地址是当我们用户同意授权后,程序会进行对回调地址的访问。所以回调地址必须在公网上能够进行访问的。(用我自己的理解就相当于是你给腾讯平台发送请求,获取用户的信息,当你参数携带正确的情况下,腾讯就会向你发送一个请求,而这个请求的路径就是上面的redirect_uri所指的路径,所以回调函数的调用只有可能在公网上进行调用)
参考文献
