问题
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='
I have never done curl requests, I don't know what to do, especially with Retrofit and it's interfaces.
I took a look at this
How to make a CURL request with retrofit?
but this guy doesnt have a -d thing
回答1:
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);
}
Where the authorization field is using the @Header solution give on your linked question.
Usage would be like --
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();
}
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);
}
来源:https://stackoverflow.com/questions/33580568/curl-u-request-with-retrofit