微信网页授权
参考微信开放文档
1.第一步:用户同意授权,获取code:
通过微信客户端发送示例连接获取code:https://open.weixin.qq.com/connect/oauth2/authorize?appid=------&redirect_uri=
https://waltonleewx.mynatapp.cc/------/oauth2&response_type=code&scope=snsapi_userinfo#wechat_redirect
授权作用域(scope参数)拥有snsapi_userinfo
点击连接,就会出现授权页面
同样,我们也可以通过web开发者工具获取code
用户同意授权后
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE
可以看到已经获取到了code值: code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期
2.第二步:通过code换取网页授权access_token
获取code后,通过链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
使用工具类发送get和post请求
3.第三步:拉取用户信息(需scope为 snsapi_userinfo)
使用工具类发送get和post请求
获取到用户信息
到这里通过微信网页授权机制,来获取用户基本信息即完成了,
下面分享一个Java发送get和post请求工具类给大家:转载至熊猫小灰:简单Http发送get和post请求工具类
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author liangyehui
* @version v1.0
* @create 2018/7/10
**/
public class HttpClientUtil {
/**
* get请求,参数拼接在地址上,即http://test.com?a=1&b=2
*
* @param url 请求地址加参数
* @return 响应
*/
public static String get(String url) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
if (response != null && response.getStatusLine()<