我想在Retrofit 2.0中实现curl post
,我该怎么做?
curl -v -X POST http://example.com/api/oauth/token
-u "appid:appsecret"
--data-urlencode "grant_type=authorization_code"
--data-urlencode "code=zzs88A"
--data-urlencode "redirect_uri=http://mydomain/show_redirect"
答案 0 :(得分:2)
我猜是这样的:
public interface AuthResource {
@FormUrlEncoded
@POST("/oauth/token")
Response auth(@Header("Authorization") String authorization,
@Field("grant_type") String grantType,
@Field("code") String code,
@Field("redirect_uri") String redirectUri);
}
并且
public static void main(String[] args) {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://example.com/api")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
String basic = "Basic " + Base64.encodeAsString("appid:appsecret");
Response response = adapter.create(AuthResource.class).auth(
basic,
"authorization_code",
"zzs88A",
"http://mydomain/show_redirect");
}
答案 1 :(得分:0)
以下是我对我的项目所做的事情,恕我直言,你可以参考:
使用curl:
C:\Users\bnk>curl --data-urlencode "grant_type=password" --data-urlencode "username=bnk" --data-urlencode "password=bnk123" http://myserver/api/token
{"access_token":"UxEXCi_OMXqrY9DWZCh3RMNAPtu0KeaVibj6u8MTPGOSb4G-...vE7nw0KRoT19OE","token_type":"bearer","expires_in":1209599,"userName":"bnk",".issued":"Thu, 12 Nov 2015 01:13:26 GMT",".expires":"Thu, 26 Nov 2015 01:13:26 GMT"}
使用Retrofit (compile 'com.squareup.retrofit:retrofit:1.9.0'
)
public interface WebAPIService {
@FormUrlEncoded
@POST("/api/token")
void getAccessToken(@Field("grant_type") String grant_type, @Field("username") String username, @Field("password") String password, Callback<JSONObject> callback);
}
然后在Activity类中:
// creating a RestAdapter using the custom client
mRestAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL_BASE)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(mOkHttpClient))
.build();
WebAPIService webAPIService = mRestAdapter.create(WebAPIService.class);
Callback callback = new Callback() {
@Override
public void success(Object o, Response response) {
String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());
Log.i(LOG_TAG, bodyString);
}
@Override
public void failure(RetrofitError retrofitError) {
Log.e(LOG_TAG, retrofitError.toString());
}
};
webAPIService.getAccessToken("password", "bnk", "bnk123", callback);
Logcat输出:
11-11 20:25:36.530 11708-11708/com.example.asyncretrofit I/AsyncRetrofit: {"access_token":"cUoWmRZfepS88PJz5lLkog6ojsJnVaH_...DEabubF3dA1USm2kCI","token_type":"bearer","expires_in":1209599,"userName":"bnk",".issued":"Thu, 12 Nov 2015 01:26:55 GMT",".expires":"Thu, 26 Nov 2015 01:26:55 GMT"}
希望这有帮助!