安卓轮子之Retrofit的使用

本文详细介绍了Retrofit在安卓开发中的应用,包括表单请求、GET方式请求JSON数据并使用GSON解析、自定义Converter和CallAdapter,以及Retrofit中URL的组合规则。同时,还展示了如何实现自定义Converter.Factory和CallAdapter.Factory,以适应不同的需求。
摘要由CSDN通过智能技术生成

表单请求

1. 普通表单

@FormUrlEncoded:表示请求体是一个 Form 表单

Content-Type:application/x-www-form-urlencoded

采用 @Field 注解:

@FormUrlEncoded
@POST("login/login")
Call<ResponseBody> login(@Field("mail") String mail, @Field("password") String password);

采用 @FieldMap 注解:

@FormUrlEncoded
@POST("login/login")
Call<ResponseBody> login(@FieldMap Map<String, String> map);

2. Mutipart 表单

@Multipart:表示请求体是一个支持文件上传的 Form 表单

Content-Type:multipart/form-data

@Part 注解支持的类型有:

  • @Part MultipartBody.Part
  • @Part("name") RequestBody name
  • @PartMap Map<String, RequestBody>

除了 okhttp3.MultipartBody.Part 之外,其他类型都必须带上表单字段,因为 okhttp3.MultipartBody.Part 中已经包含了表单字段的信息。

@Multipart
@POST("FileServlet?style=UploadFiles")
Call<ResponseBody> uploadFiles(@Part MultipartBody.Part filePart);
// @Part("name") RequestBody requestBody

上传示例:

File file = new File("D:\\test.txt");
String partName = "file";
String fileName = file.getName();
final MediaType MEDIA_OBJECT_STREAM =
        MediaType.parse("application/octet-stream; charset=UTF-8");
RequestBody fileBody = RequestBody.create(MEDIA_OBJECT_STREAM, file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData(partName, fileName, fileBody);
Call<ResponseBody> uploadFile = inteCastService.uploadFiles(filePart);

GET 方式请求 JSON 数据并解析得到 GSON 对象

// Repo 是由 Android Studio 插件 GsonFormat 从 JSON 字符串自动生成的类

interface GithubService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}

private void connect() {
    Retrofit retrofit = new Retrofit.Builder()
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值