★39.Retrofit

2017-06-29  本文已影响0人  iDragonfly

简介

简单示例

1. 定义Model

public interface WebModel {
    // 此字符串会拼接在baseUrl后面,其中{id}是占位符,可以用@Path后接的参数替换。
    @GET("something/{id}/")
    Call<ResponseBody> getWeb(@Path("id") int id);

    @POST("form")
    @FormUrlEncoded
    Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
}

2. 创建OkHttpClient

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
        .readTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(9, TimeUnit.SECONDS)
        .build();

3. 创建Retrofit

Retrofit retrofit = new Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl("https://www.baidu.com/")
        .build();

4. 创建Model

WebModel service = retrofit.create(WebModel.class);

5. 创建Call

Call<ResponseBody> call = service.getWeb(2);

6. 执行Call

call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            // UI线程
            Log.d("MyTag", response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        t.printStackTrace();
    }
});

Model注解

1. HTTP请求方法

@HTTP注解

public interface WebModel {
    @HTTP(method = "get", path = "blog/{id}", hasBody = false)
    Call<ResponseBody> getWeb(@Path("id") int id);
}

2. 标记类及其示例

标记类注解

1. 定义Model

0. 外壳

public interface BlogService {
    // ...
}

1. 演示@FormUrlEncoded@Field

@POST("form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);

2. 演示@FormUrlEncoded@FieldMap

@POST("form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);

3. 演示@Multipart@Part

@POST("form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);

4. 演示@Multipart@PartMap

@POST("form")
@Multipart
Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args);

2. 创建Call

1. 演示@FormUrlEncoded@Field

Call<ResponseBody> call1 = service.testFormUrlEncoded1("name", 24);

2. 演示@FormUrlEncoded@FieldMap

Map<String, Object> map = new HashMap<>();
map.put("username", "name");
map.put("age", 24);
Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);

3. 演示@Multipart@Part

RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "怪盗kidou");
RequestBody age = RequestBody.create(MediaType.parse("text/plain"), "24");

RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "这里是模拟文件的内容");
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);

Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);

4. 演示@Multipart@PartMap

// 实现和@Multipart和@Part同样的效果,但是文件要单独处理,因为文件是由键、文件名(包含在Content-Disposition请求头中)、文件内容组成的,不是普通的键值对。
Map<String, RequestBody> fileUpload2Args = new HashMap<>();
fileUpload2Args.put("name", name);
fileUpload2Args.put("age", age);
Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart);

3. 参数类

1. 定义Model

0. 外壳

public interface BlogService {
    // ...
}

1. 演示@Headers@Header

@GET("/headers?showAll=true")
@Headers({"CustomHeader1: customHeaderValue1", "CustomHeader2: customHeaderValue2"})
Call<ResponseBody> testHeader(@Header("CustomHeader3") String customHeaderValue3);

2. 演示@Query

// 效果:ids[]=ids1&ids[]=ids2
Call<ResponseBody> foo(@Query("ids[]") boolean ids1, @Query("ids[]") boolean ids2);
// 效果:ids[]=0&ids[]=1&ids[]=2
Call<ResponseBody> foo(@Query("ids[]") List<Integer> ids);

3. 演示@QueryMap【Todo】

4. 演示@Url

@GET
Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);

注意事项

上一篇 下一篇

猜你喜欢

热点阅读