<td>@Body </td>
payload for the POST call |
</tr>
</tbody>
</table>
修改 base URL
一般地,base URL是在實例化 Retrofit instance 的時候定義的。Retrofit 2 允許你在注解里面重寫base URL 。
@POST("https://api.github.com/api/v3")
就如 這篇文章 (中文地址:Retrofit 2.0)所討論的,還有一些允許你使用相對路徑(不是完整的URL)修改 base URL的方法。
Multipart forms
如果你要提交多參數表單數據(multi-part form data),可以使用@Multipart與@Part注解:
@Multipart
@POST("/some/endpoint")
Call<SomeResponse> someEndpoint(@Part("name1") String name1, @Part("name2") String name2)
Form URL encoding
如果我們希望提交 form-encoded name/value ,我們可以使用@FormUrlEncoded 與 @FieldMap注解:
@FormUrlEncoded
@POST("/some/endpoint")
Call<SomeResponse> someEndpoint(@FieldMap Map<String, String> names);
Upgrading from Retrofit 1
如果你是想從 Retrofit 1升級過來,你應該記得在1.x版本中,如果你想定義一個異步的API請求而非同步請求,最后一個參數必須是Callback類型:
public interface MyApiEndpointInterface {
// Request method and URL specified in the annotation
// Callback for the parsed response is the last parameter
@GET("/users/{username}")
void getUser(@Path("username") String username, Callback<User> cb);
@GET("/group/{id}/users")
void groupList(@Path("id") int groupId, @Query("sort") String sort, Callback<List<User>> cb);
@POST("/users/new")
void createUser(@Body User user, Callback<User> cb);
}
Retrofit 1 依賴于這個Callback類型作為最后一個參數,決定api請求是異步的。為了避免出現兩種不同的調用模式,這個接口在Retrofit 2被統一了。現在你可以直接定義返回值為一個參數化了的Call<T>,如前面小節所講。
Accessing the API
我們現在可以把這些東西放在一起:
MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
如果我們想異步請求這個API,我們如下調用這個service (注意取名為service 是Retrofit 的慣例,并不是語法的一部分):
String username = "sarahjean";
Call<User> call = apiService.getUser(username);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response) {
int statusCode = response.code();
User user = response.body();
}
@Override
public void onFailure(Throwable t) {
// Log error here since request failed
}
});
如上所示,Retrofit 將在后臺線程下載與解析API數據,然后通過onResponse或者 onFailure方法把結果發送回UI線程。
Retrofit與Authentication
使用Authentication Headers
可以使用一個Interceptor來為請求添加Headers。要發送請求到一個authenticated API,如下:
// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("User-Agent", "Retrofit-Sample-App").build();
return chain.proceed(newRequest);
}
};
// Add the interceptor to OkHttpClient
OkHttpClient client = new OkHttpClient();
client.interceptors().add(interceptor);
// Set the custom client when building adapter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
注意在Retrofit 2中,interceptor 必須添加到一個自定義的OkHttpClient。而在Retrofit 1,它可以直接被builder 類設置。
Using OAuth
In order to authenticate with OAuth, we need to sign each network request sent out with a special header that embeds the access token for the user that is obtained during the OAuth process. The actual OAuth process needs to be completed with a third-party library such as signpost and then the access token needs to be added to the header using a request interceptor . Relevant links for Retrofit and authentication below:
Resources for using signpost to authenticate with an OAuth API:
Several other Android OAuth libraries can be explored instead of signpost:
參考
本文由用戶
jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
sesese色