Retrofit2 数据请求方式

服务器使用Post请求时会要求设置传入请求参数的类型。这种情况下通常需要指定参数为RequestBody,如下

Call<ResponseBody> register(@Body RequestBody body)

同时该参数的构造如下。针对字符串默认使用UTF_8

#字符串#
public static RequestBody create(@Nullable MediaType contentType, String content) 

#文件#
public static RequestBody create(final @Nullable MediaType contentType, final File file)

#字节流#
public static RequestBody create(final @Nullable MediaType contentType, final byte[] content)

public static RequestBody create(final @Nullable MediaType contentType, final byte[] content,
      final int offset, final int byteCount)

参数类型:
通过MediaType 指定参数类型

1、普通类型
不需要使用 RequestBody作为参数,直接使用@Field 拼接参数即可
参数的表现形式

username=xxxpassword=xxx&type=0

2、json类型

MediaType.parse("application/json; charset=utf-8")

参数表现形式

{“username”:”xxx”,”password”:”xxx”,”type”:0}

3、文件类型
系统额外的信息,通过MultipartBody的方式

RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
          .addFormDataPart("name", name)//额外信息
          .addFormDataPart("pwd", pwd)//额外信息
          .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
          .build();

不需要额外的信息,使用普通的RequestBody

RequestBody requestFile =              RequestBody.create(MediaType.parse("multipart/form-data"), file)

4、表单提交

MediaType.parse("multipart/form-data")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值