一.先看一個(gè)完整的例子:
package com.github.ikidou;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Path;
/**
* [Retrofit入門]源碼
*/
public class Example01{
public interface BlogService{
@GET("blog/{id}")//這里的{id} 表示是一個(gè)變量
CallgetBlog(/** 這里的id表示的是上面的{id}*/@Path("id")intid);
? ? }
public static void main(String[]args)throws IOException{
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
? ? ? ? ? ? ? ? .build();
BlogService service = retrofit.create(BlogService.class);
Call call=service.getBlog(2);
//用法和OkHttp的call如出一轍
//不同的是如果是Android系統(tǒng)回調(diào)方法執(zhí)行在主線程
call.enqueue(new Callback() {
@Override
public void onResponse(
Call call , Response response) {
try{
System.out.println(response.body().string());
}catch(IOExceptione) {
e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
@Override
public void onFailure(Callcall,Throwablet) {
t.printStackTrace();
? ? ? ? ? ? }
? ? ? ? });
? ? }
}
二.進(jìn)行拆解分析:
public interface BlogService{
@GET("blog/{id}")//這里的{id} 表示是一個(gè)變量
CallgetBlog(/** 這里的id表示的是上面的{id}*/@Path("id")intid);
? ? }
這個(gè)接口算是retrofit里面的重要部位.
@GET("blog/{id}")代表注解,不清楚的可以google或者百度了解一下.
{id}在@GET注解中,指CallgetBlog(@Path("id")int id);這個(gè)函數(shù)里面的id,后期調(diào)用函數(shù)CallgetBlog將會(huì)傳入?yún)?shù)id.
可以使用方法中的替換塊和參數(shù)動(dòng)態(tài)更新請(qǐng)求URL抑堡。
讀懂下面這幾句話:
Use annotations to describe the HTTP request:
URL parameter replacement and query parameter support
Object conversion to request body (e.g., JSON, protocol buffers)
Multipart request body and file upload
以上就是注解相關(guān)傳參方式解釋.
如果自學(xué)能力強(qiáng),英文基礎(chǔ)好的,可以直接在官網(wǎng)學(xué)習(xí)
1.REQUEST METHOD(請(qǐng)求方法)
Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the annotation.
Query parameters(查詢參數(shù)) can also be added.
比如從服務(wù)器上獲取新聞信息等.
@GET("group/{id}/users")Call> groupList(@Path("id") int groupId, @Query("sort") String sort);
//@Query將在url地址中追加類似“page=1”的字符串壁畸,形成提交給服務(wù)端的請(qǐng)求參數(shù)
2.對(duì)于復(fù)雜的查詢參數(shù)組合递惋,可以使用MAP。
@GET("group/{id}/users")
Call<List<User>>groupList(@Path("id") int groupId , @QueryMap Map options);
@QueryMap Map?options這個(gè)并不是要像@Path一樣拼接進(jìn)參數(shù).
3.REQUEST BODY(請(qǐng)求體形式)
An object can be specified for use as an HTTP request body with the?@Body?annotation.
@POST("users/new")
Call<User>createUser(@Body User user);
4. FORM ENCODED AND MULTIPART(上傳信息)
Methods can also be declared to send form-encoded and multipart data.Form-encoded data is sent when?@FormUrlEncoded?is present on the method. Each key-value pair is annotated with?@Fieldcontaining the name and the object providing the value.
@FormUrlEncoded
@POST("user/edit")
Call<User>?updateUser(@Field("first_name") String first, @Field("last_name") String last);
Multipart requests are used when?@Multipart?is present on the method. Parts are declared using the?@Part?annotation.
@Multipart
@PUT("user/photo")
Call<User>?updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
5.HEADER MANIPULATION
注意遗淳,頭文件不會(huì)覆蓋彼此轧膘。所有具有相同名稱的頭將包含在請(qǐng)求中(如果不清楚的可以先大概學(xué)習(xí)HTTP請(qǐng)求相關(guān)知識(shí))
You can set static headers for a method using the?@Headers?annotation.
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>>?widgetList();
@Headers({
? ? "Accept: application/vnd.github.v3.full+json",
? ? "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User>?getUser(@Path("username") String username); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
A request Header can be updated dynamically using the?@Header?annotation. A corresponding parameter must be provided to the?@Header. If the value is null, the header will be omitted. Otherwise,?toString?will be called on the value, and the result used.
@GET("user")
Call<User>?getUser(@Header("Authorization") String authorization)