当前位置 博文首页 > 超负荷小生的博客:OAuth2.0微博登录的坑
error":“invalid_request”,“error_code”:21323,“request”:"/oauth2/access_token",“error_uri”:"/oauth2/access_token",“error_description”:"miss client id or secret“
该接口要求提交的参数在url中,提交的数据体要设置为空。
使用OKhttp发送请求
import okhttp3.*;
import java.io.IOException;
public class OkHttpUtils {
public String OkHttpDoPost(String url, String param)throws IOException{
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public String OkHttpDoGet(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
调用微博接口时要使用post,提交的数据为空:
public void WeiBoLogin(String code) throws IOException {
OkHttpUtils okHttpUtils = new OkHttpUtils();
Map<String,String> map = new HashMap<>();
String param = JSON.toJSONString(map);
// 微博要求必须将参数在链接中,post形式发送,并且提交的参数是空
//https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
//拿到code ,构造url,使用OKhttp的post方式
String url = "https://api.weibo.com/oauth2/access_token?client_id="+client_id+"&client_secret="+client_secret+"&grant_type=authorization_code&redirect_uri="+redirect_uri+"&code="+code;
String accessTokenResult = okHttpUtils.OkHttpDoPost(url, param);
System.out.println(accessTokenResult);
}
报错:
okhttp3.MediaType.get(Ljava/lang/String;)Lokhttp3/MediaType;
该报错依赖有冲突
解决:
1.springboot项目,在pom.xml中不填写版本号,使用默认提供的版本。
2.根据对应的版本更改MediaType.get中的参数等问题