带有翻新的CURL -u请求

问题描述:

我正在Android中使用Retrofit(不是新的)来执行一些OAuth授权。
我已经走过第一步,可以使用代码,现在规范中的下一件事就是这样做:

I am using Retrofit (not the new one) in Android to do some OAuth authorization. I am past the first step where I get a code to use, now the next thing in the specifications is to do this:

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

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

I have never done curl requests, I don't know what to do, especially with Retrofit and it's interfaces.

看看这个

如何通过改造来发出CURL请求?

但是这个家伙没有-d东西

but this guy doesnt have a -d thing

curl的 -d 参数添加POST参数。在这种情况下, grant_type code 。我们可以使用 @Field 批注对每个编码进行编码。

The -d argument to curl adds POST parameters. In this case, grant_type and code. We can encode each of those in retrofit with the @Field annotation.

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 解决方案给出您所链接的问题。

Where the authorization field is using the @Header solution give on your linked question.

用法就像-

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 是您的链接答案中的帮助方法。为完整起见,在下面复制-

where getBase64String is helper method from your linked answer. Copied below for completeness --

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