CURL -u 请求与改造

CURL -u request with Retrofit

我在 Android 中使用 Retrofit(不是新的)来做一些 OAuth 授权。 我已经完成了获得要使用的代码的第一步,现在规范中的下一步是执行此操作:

curl -u : http://example.com/admin/oauth/token -d 'grant_type=authorization_code&code='

我从未做过 curl 请求,我不知道该怎么做,尤其是 Retrofit 及其接口。

我看了这个

How to make a CURL request with retrofit?

但这家伙没有 -d 东西

curl 的 -d 参数添加了 POST 个参数。在这种情况下,grant_typecode。我们可以使用 @Field 注释对改造中的每一个进行编码。

public interface AuthApi {
    @FormUrlEncoded
    @POST("/admin/oauth/token")
    void getImage(@Header("Authorization") String authorization,
                        @Field(("grant_type"))String grantType,
                        @Field("code") String code,
                        Callback<Object> callback);
}

授权字段使用 @Header 解决方案给出您的链接问题。

用法就像 --

RestAdapter authAdapter = new RestAdapter.Builder().setEndpoint("http://example.com/").build();
AuthApi authApi = authAdapter.create(AuthApi.class);

try {
    final String auth = "Basic " + getBase64String(":");
    authApi.getImage(auth, "authorization_code", "", new Callback<Object>() {
        @Override
        public void success(Object o, Response response) {
            // handle success
        }

        @Override
        public void failure(RetrofitError error) {
            // handle failure
        }
    });
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

其中 getBase64String 是您链接答案中的辅助方法。为了完整起见复制如下 --

public static String getBase64String(String value) throws UnsupportedEncodingException {
    return Base64.encodeToString(value.getBytes("UTF-8"), Base64.NO_WRAP);
}