刚开始接触 Retrofit,正在尝试使用 Retrofit 来使用 Instagram API。下面是设置。 首先,我定义与 Instagram API 通信的接口(interface)
public interface API {
@POST("oauth/access_token")
Call<AccessToken> getAccessToken(@Body TokenRequest tokenRequest);
}
下面是我的实现
public class APIPresenter implements Callback<List<APIResponse>> {
static final String BASE_URL = "https://api.instagram.com/";
public void startI(String code){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
API r = retrofit.create(API.class);
Call<AccessToken> call = r.getAccessToken(new TokenRequest("CLIENT_ID", "CLIENT_SECRET", "authorization_code", "redirecturi", code));
call.enqueue(new Callback<AccessToken>() {
@Override
public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
// Log.i("WORKING", response.body().access_token + " " + response.body().user.getUsername());
Log.i("WORKING", String.valueOf(response.code()));
}
@Override
public void onFailure(Call<AccessToken> call, Throwable t) {
t.printStackTrace();
}
});
}
token 请求
public class TokenRequest {
private String client_id;
private String client_secret;
private String grant_type;
private String redirect_uri;
private String code;
public TokenRequest(String client_id, String client_secret, String grant_type, String redirect_uri, String code) {
this.client_id = client_id;
this.client_secret = client_secret;
this.grant_type = grant_type;
this.redirect_uri = redirect_uri;
this.code = code;
}
}
AccessToken模型
public class AccessToken {
@SerializedName("access_token")
@Expose
public String access_token;
@SerializedName("user")
@Expose
public User user;
}
问题是,当我尝试在 onResponse 方法中输出响应内容时,我得到一个 null。我不确定我做错了什么
更新 我收到以下错误消息
{"code": 400, "error_type": "OAuthException", "error_message": "You must provide a client_id"}
最佳答案
我设法解决了这个问题,问题是 Instagram 不支持将参数作为 URL 参数发送,它们必须在 POST 的正文内容中发送。 内容类型应设置为“application/x-www-form-urlencoded”。
这就是您如何使用上面的代码来完成它
必须在POST方法前添加@FormURLEncoded注解,这只能使用@Field注解,因此@Body内容应替换为以下@Field注解。
public interface API {
@FormURLEncoded
@POST("oauth/access_token")
Call<AccessToken> getAccessToken(
@Field("client_id") String client_id,
@Field("client_secret") String client_secret,
@Field("grant_type") String grant_type,
@Field("redirect_uri") String redirect_uri,
@Field("code") String code);
}
这是您将详细信息发送到接口(interface)上的 getAccessToken 方法的方式
Call<AccessToken> call = r.getAccessToken("CLIENT_ID", "CLIENT_SECRET", "authorization_code", "redirecturi", code);
这应该可以完美地工作!
关于java - Retrofit + Instagram API 在请求访问 token 时返回错误 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193697/