Retrofit 初体验--常用的注解字段

2019-01-03  本文已影响0人  NullPoint3Exce

需要掌握的注解字段
Get Post Url Query QueryMap Field FieldMap Path Body Part MiulPart Header Headers FormUrlEncode

retrofit的简单实现:
依赖:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

权限: <uses-permission android:name="android.permission.INTERNET"/>

  Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.xxxx.com") // 添加请求地址
                .addConverterFactory(GsonConverterFactory.create())//使用gson库解析
                .build();
        IFoodService iFoodService = retrofit.create(IFoodService.class);
        Call<ResponseBody> call = iFoodService.getFoodList();
        call.enqueue(new Callback<ResponseBody>() {
....此处忽略
@GET("/ios/cf/dish_list.php?stage_id=1&limit=20")
Call<ResponseBody> getFoodList(@Query("page") String page);
 

请求接口的声明:

   @GET("/banner/json/")
    Call<ResponseBody> getFoodList();

到这里一个简单的get请求的逻辑,就实现了!

@FormUrlEncoded
@POST("v1/login")
Call<ResponseBody> userLogin(@Field("phone") String phone, @Field("password") String password);
 
@Headers("apikey:b86c2269fe6588bbe3b41924bb2f2da2")
@GET
Call<WeatherWrapper> weather(@Url String url, @Query("cityname") String cityName);

@GET("/ios/cf/dish_list.php?stage_id=1&limit=20")
Call<ResponseBody> getFoodList(@Query("page") String page);
 
Call<ResponseBody> getFoodList(@QueryMap Map<String, String> options);
@FormUrlEncoded
@POST("v1/login")
Call<ResponseBody> userLogin(@Field("phone") String phone, @Field("password") String password);
 
@FormUrlEncoded
@POST("book/reviews")
Call<String> addReviews(@FieldMap Map<String, String> fields);
@GET("blog/{id}")
Call<ResponseBody> getBlog(@Path("id") int id);   
@POST("users/new")
Call<User> createUser(@Body User user);
@Multipart
@POST("upload")
Call<ResponseBody> uploadOneFile(@Part MultipartBody.Part body);
      // Headers的使用
@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);

// Header的使用
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
上一篇 下一篇

猜你喜欢

热点阅读