Retrofit2.0基础用法

来源:互联网 发布:淘宝客推广联盟教程 编辑:程序博客网 时间:2024/05/16 10:34

最近看到Retrofit很火所以是时候出击学习了。学习过程如下:

一、Retrofit使用方法

以下使用的都是最新包
1、AndroidManifest.xml有网络权限

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    <uses-permission android:name="android.permission.INTERNET" /></manifest>

2、在你app/build.gradle文件中添加下面依赖

dependencies {    compile 'com.google.code.gson:gson:2.6.2'    compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'  }

3、如果你想使用RxJava和Retrofit 2,添加RxJava Adapter

dependencies {  compile 'io.reactivex:rxjava:1.1.6'  compile 'io.reactivex:rxandroid:1.2.1'  compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'}

4、创建Retrofit对象,指定接口的基本地址

public static final String BASE_URL = "http://uu.newerest.com/index.php/";Retrofit retrofit = new Retrofit.Builder()    .baseUrl(BASE_URL)    .addConverterFactory(GsonConverterFactory.create())    .build();

5、创建API接口

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);}

注意:如果想了解更多注释含义以及GET和POST请求方式的不同,请查看Retrofit2.0的API文档

6、实现接口服务

MyApiEndpointInterface apiService =    retrofit.create(MyApiEndpointInterface.class);Call<User> call = apiService.getUser("sarahjean");call.enqueue(new Callback<User>() {    @Override    public void onResponse(Call<User> call, Response<User> response) {        int statusCode = response.code();        User user = response.body();      }    @Override    public void onFailure(Call<User> call, Throwable t) {        // Log error here since request failed    }});

Retrofit的基本使用就是以上这样一个流程。

二、GET 和POST的区别

对于Retrofit 2, 端点被定义在一个接口内部,使用特殊的改造注释来对参数和请求方法的细节进行编码。此外,请求的返回值通常是Call对象,比如Call返回User对象。如果你不想不需要任何特定类型的响应,你可以指定返回值为Call。

  • GET请求方式
 @GET("users/{username}")    Call<User> getUser(@Path("username") String username);    @GET("group/{id}/users")    Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
  • POST请求方式

假如请求参数是一组JSON字符串,有两种方式,如下。

/**     * 组合的参数形成JSON字符串     */    @FormUrlEncoded    @POST("Scenic/getList")    Call<Spot> getSpotPost(@Field("client_id") String cId, @Field("client_secret") String cSecret);    /**     * 参数比较多的时候可以用FieldMap替代     */    @FormUrlEncoded    @POST("Scenic/getList")    Call<Spot> getSpot(@FieldMap Map<String, String> map);

而@Path、@Query、@Field等等的注释的含义如下:
注释 描述
@Path 用于该接口的变量替换(username将替换在URL端点的{username})
@Query 带注释参数值的指定查询键名称
@Body POST的有效负载(序列化的java对象转化为JSON字符串)
@Header 指定带有批注参数的值的标题

Form data

如果我们希望提交表单编码的数据,我们可以使用FormUrlEncoded注释。@Field将表示将提交哪些有效负载作为表单数据。

@FormUrlEncoded @POST("/some/endpoint") Observable someEndpoint(@Field("code") String code);

Multipart forms

如果你想上传文件或者图片,你需要将采用多形式方式上传。使用@Multipart标记,最少有一个@Part参数

@Multipart@POST("some/endpoint")Call<Response> uploadImage(@Part("description") String description, @Part("image") RequestBody image)

如果有一个参考的文件,可以创建一个requestbody对象:

MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");file = new File("/storage/emulated/0/Pictures/MyApp/test.png");RequestBody requestBody = RequestBody.create(MEDIA_TYPE_PNG, file);Call<Response> call = apiService.uploadImage("test", requestBody);

三、Retrofit实例

Retrofit 示例代码

2 0
原创粉丝点击