以下是我已經跟我的項目,恕我直言,這樣做,你可以參考:
使用捲曲:
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"}
使用改造(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);
}
然後活動類中:
// 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"}
希望這會有所幫助!
來源
2015-11-12 01:35:24
BNK
你可以看到答案。順便說一句,你甚至嘗試過什麼?你有什麼問題?據我所知Retrofit有很好的文檔http://square.github.io/retrofit/ –
我試過Retrofit,但我得到服務器錯誤500,但在瀏覽器中一切都很好!我測試你的代碼並讓你知道。 – AVEbrahimi