【发布时间】:2015-12-31 07:19:55
【问题描述】:
我正在尝试实现 OAuth2。我需要将它用于我的学校项目 - 学校提供了一些文档,它说我需要调用它
POST /oauth/token HTTP/1.1
Host: oaas.example.org
Authorization: Basic ZHVtbXktY2xpZW50OnRvcC1zZWNyZXQ=
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=l1kSf2&redirect_uri=https://client.example.org/auth
或者有卷曲的样本
curl --data "grant_type=authorization_code&code=l1kSf2&redirect_uri=https://client.example.org/auth" \
--user dummy-client:top-secret https://oaas.example.org/oauth/token
但我不知道如何将其转移到 Android 通话中。我目前正在使用 Retrofit,reguest 就像 JSON:
POST /oauth/oauth/token/DeviceAndroid HTTP/1.1
Authorization: Basic OGRkOGJiZGMtOGI2NC00NTdlLTgwYWMtZmE5NDZjNzY4Njgzc0owY3RKV2VWNHFLY0dwWHNIOGEzcDVYYUl0NDRGN2o=
Content-Type: application/x-www-form-urlencoded
Content-Length: 85
Host: auth.fit.cvut.cz
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/2.5.0
{"code":"p1P3os","grant_type":"authorization_code","redirect_uri":"http://localhost"}
我的网络接口
public interface NetworkInterface {
String TAG = NetworkInterface.class.getName();
String URL = "https://auth.fit.cvut.cz";
@Headers("Content-Type: application/x-www-form-urlencoded")
@POST("/oauth/oauth/token/DeviceAndroid")
Call<Object> sendInformationToServer(@Body RequestToken requestToken);
}
请求令牌
public class RequestToken {
public static final String TAG = RequestToken.class.getName();
public String grant_type;
public String code;
public String redirect_uri;
...
服务生成器
public class ServiceGenerator {
private static OkHttpClient httpClient = new OkHttpClient();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(NetworkInterface.URL)
.addConverterFactory(GsonConverterFactory.create());
public static <T> T createService(Class<T> serviceClass , final String autorizationString) {
httpClient = new OkHttpClient();
if (autorizationString != null) {
httpClient.interceptors().clear();
httpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Basic " + RequestToken.returnBase64(autorizationString))
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
有没有办法用改造(或不同的方法)来称呼它,在此先感谢
【问题讨论】:
-
如果你的需求是
POST /oauth/token,那你的代码为什么是POST /oauth/oauth/token/DeviceAndroid? -
另外,您正在发布 JSON,而不是 url 编码数据。请参阅此答案以供参考。 stackoverflow.com/a/28291203/2308683