前言
A type-safe HTTP client for Android and Java.(Github)
创建发送请求接口
常用的注解
/:请求地址URL资源路径
@GET(""):在接口上标注@GET("")表示发送GET请求,在注解参数中填写服务器接口请求地址,不需要涵盖域名
@Query(""):使用GET请求传递参数时,需要在参数前添加@Query()注解,注解内指定发送请求时的参数名
@POST(""):在接口上标注@POST("")表示发送POST请求,在注解参数中填写服务器接口请求地址,不需要涵盖域名
@Field(""):使用POST请求传递参数时,如果是FormUrlEncoded的方式,需要在参数前添加@Field()注解,注解内指定发送请求时的参数名
app/src/main/java/.../HttpBinService.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query;
public interface HttpBinService {
@GET("/") Call<ResponseBody> get(@Query("username") String username, @Query("password") String password);
@POST("/") @FormUrlEncoded Call<ResponseBody> post(@Field("username") String username, @Field("password") String password);
}
|
Map注解
app/src/main/java/.../HttpBinService.java1 2
| @GET("/") Call<ResponseBody> GET(@QueryMap Map<String, Object> map);
|
app/src/main/java/.../HttpBinService.java1 2 3
| @POST("/") @FormUrlEncoded Call<ResponseBody> POST(@FieldMap Map<String, Object> map);
|
@HTTP注解
利用@HTTP注解定义GET请求
method = "GET":定义请求方法
path = "":定义请求地址
hasBody = false:定义是否有请求体,默认不填为false
1
| @HTTP(method = "GET", path = "/")
|
1
| @HTTP(method = "GET", path = "/", hasBody = false)
|
利用@HTTP注解定义POST请求
method = "POST":定义请求方法
path = "":定义请求地址
hasBody = false:定义是否有请求体,默认不填为false
1
| @HTTP(method = "POST", path = "/")
|
1
| @HTTP(method = "POST", path = "/", hasBody = false)
|
1
| @HTTP(method = "POST", path = "/", hasBody = true)
|
@Path注解
动态传递请求地址的资源路径部分
1 2
| @HTTP(method = "", path = "{pathname}") Call<ResponseBody> get(@Path("pathname") String urlPathname);
|
与@HTTP注解配合实现动态请求方法
1 2
| @HTTP(method = "{method}", path = "") Call<ResponseBody> get(@Path("method") String method);
|
key:请求头参数键
value:请求头参数值形参
1 2
| @GET("/") Call<ResponseBody> get(@Header("key") String value);
|
- @Headers注解用于直接在方法上标注请求头所有参数
添加一个参数
1 2 3
| @Headers("key:value") @GET("/") Call<ResponseBody> get();
|
添加多个参数
1 2 3
| @Headers({"key1:value1", "key2:value2"}) @GET("/") Call<ResponseBody> get();
|
创建Retrofit对象
<url>:请求地址URI的URL部分
发送GET请求
app/src/main/java/.../MainActivity.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| Retrofit retrofit = new Retrofit.Builder().baseUrl("<url>").build();
HttpBinService httpBinService = retrofit.create(HttpBinService.class);
Call<ResponseBody> responseBodyCall = httpBinService.get("", ""); responseBodyCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } }
@Override public void onFailure(Call<ResponseBody> call, Throwable t) {
} });
|
发送POST请求
app/src/main/java/.../MainActivity.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| Retrofit retrofit = new Retrofit.Builder().baseUrl("<url>").build();
HttpBinService httpBinService = retrofit.create(HttpBinService.class);
Call<ResponseBody> responseBodyCall = httpBinService.post("", ""); responseBodyCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } }
@Override public void onFailure(Call<ResponseBody> call, Throwable t) {
} });
|
POST请求传递JSON参数
通过JSON格式的字符串直接传递字符串
app/src/main/java/.../HttpBinService.java1 2 3
| @POST("/") @FormUrlEncoded Call<ResponseBody> POST(@Field("") String json);
|
通过@Body注解传递RequestBody对象
app/src/main/java/.../HttpBinService.java1 2 3
| @POST("/") @FormUrlEncoded Call<ResponseBody> POST(@Body RequestBody requestBody);
|
发送含有RequestBody的POST请求
app/src/main/java/.../MainActivity.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| FormBody body = new FormBody.Builder().add("", "").build();
Retrofit retrofit = new Retrofit.Builder().baseUrl("<url>").build(); HttpBinService httpBinService = retrofit.create(HttpBinService.class); Call<ResponseBody> responseBodyCall = httpBinService.post(body); responseBodyCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } }
@Override public void onFailure(Call<ResponseBody> call, Throwable t) {
} });
|
通过完整请求地址发送请求
- 通过@Url注解,将完整请求地址URI以参数的形式传递
<url>:请求的目标URL
定义接口
1 2 3 4 5 6 7 8 9
| public interface HttpBinService {
@GET Call<ResponseBody> get(@Url String url); @POST @FormUrlEncoded Call<ResponseBody> post(@Url String url); }
|
发送请求
发送GET请求
1 2 3 4 5 6 7 8
| Retrofit retrofit = new Retrofit.Builder().baseUrl("").build(); HttpBinService httpBinService = retrofit.create(HttpBinService.class); try { Response<ResponseBody> response = httpBinService.get("<url>").execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }
|
发送POST请求
1 2 3 4 5 6 7 8
| Retrofit retrofit = new Retrofit.Builder().baseUrl("").build(); HttpBinService httpBinService = retrofit.create(HttpBinService.class); try { Response<ResponseBody> response = httpBinService.post("<url>").execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }
|
Retrofit转换器
- 通过使用Retrofit提供的转换器,将响应的JSON格式的字符传数据转换成Java对象
添加依赖
app/build.gradle1 2 3 4 5 6
| dependencies {
... implementation 'com.squareup.retrofit2:converter-gson:2.9.0' }
|
创建一个实体类
1 2 3 4 5
| public class Responce {
...
}
|
在接口中的泛型直接定义为实体类
1 2 3 4 5 6
| public interface HttpBinService {
@GET("/") Call<Responce> get(@Query("username") String username, @Query("password") String password);
}
|
发送请求
1 2 3 4 5 6 7 8 9 10
| Retrofit retrofit = new Retrofit.Builder() .baseUrl("<url>") .converterFactory(GsonConverterFactory.create()) .build();
HttpBinService httpBinService = retrofit.create(HttpBinService.class);
Responce responce = httpBinService.get("", "").execute().body();
|
文件上传下载
定义接口
@Part:此处也可以使用@PartMap注解实现多文件上传
@Streaming:文件下载时可以防止内存溢出
1 2 3 4 5 6 7 8 9 10
| public interface HttpBinService {
@POST("/") @Multipart Call<ResponseBody> post(@Part MultipartBody.Part file);
@GET("/") @Streaming Call<ResponseBody> download(); }
|
文件上传下载
上传文件
<key>:请求参数键
<value>:请求参数值,通常为文件名
1 2 3 4 5 6 7 8 9 10 11 12
| File file = new File(""); MultipartBody.Part part = MultipartBody.Part.createFormData("<key>", "<value>", RequestBody.create(MediaType.parse("text/plain"), file));
Retrofit retrofit = new Retrofit.Builder().baseUrl("<url>").build(); HttpBinService httpBinService = retrofit.create(HttpBinService.class); Call<ResponseBody> call = httpBinService.upload(part); try { String result = call.execute().body().string(); System.out.println(result); } catch (IOException e) { e.printStackTrace(); }
|
下载文件
<file>:文件存放的本地路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Retrofit retrofit = new Retrofit.Builder().baseUrl("<url>").build(); HttpBinService httpBinService = retrofit.create(HttpBinService.class); Call<ResponseBody> call = httpBinService.download(); try { Response<ResponseBody> response = call.execute();
if (response.isSuccessful()) { InputStream inputStream = response.body().byteStream(); FileOutputStream fos = new FileOutputStream("<file>"); int len; byte[] buffer = new byte[4096]; while ((len = inputStream.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); inputStream.close(); } } catch (IOException e) { e.printStackTrace(); }
|
完成
参考文献
哔哩哔哩——Android架构解析