服务器使用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")