您的位置:首页 > 其它

RetroFit请求参数和返回格式说明

2017-02-10 18:53 295 查看
1 Get请求

通过@Query注解请求参数,如下:

@POST("banner/api/5item.json")

Observable<TestResponse> login(@Query("bId") String bId, @Query("name") String name);

发出的请求形式如下:
http://7xk9dj.com1.z0.glb.clouddn.com/banner/api/5item.json? bId =test1& name =test3

参数都被添加到请求Url的后面

通过@ QueryMap注解请求参数,如下:

@POST("banner/api/5item.json ")

Observable<TestResponse> login(@QueryMap Map<String, String> params);

发出的请求形式与上例一致。

2 简单Post请求

@POST("banner/api/5item.json")

Observable<TestResponse> login(@Query("p") String p, @Body TestRequest request);

其中TestRequest为请求body,如下:

public class TestRequest extends BaseRequest {

@SerializedName("request")

public Request request;

public TestRequest(){

request = new Request();

}

public static class Request{

public String wContact;

public String wSuggestion;

}

}

发出的请求形式如下:



1. P参数依然会放在url后面

2. 整个TestRequest会以json的格式放在http请求的body中传输

3 FormUrlEncoded

 通过@Field注解添加表单,如下:

@FormUrlEncoded

@POST("banner/api/5item.json")

Observable<TestResponse> login(@Field("param1 ") String param1, @Field(" param2") String param2);

 通过@FieldMap注解添加表单,如下:

@FormUrlEncoded

@POST("banner/api/5item.json ")

Observable<TestResponse> login(@FieldMap Map<String, String> params);

发出的请求形式如下:



注:这种形式和简单Post中body的数据格式是不一样的。

4 Multipart

该方式是支持上传文件的

 通过@Part注解请求参数,如下:

@Multipart

@POST("banner/api/5item.json")

Observable<TestResponse> login(@Part RequestBody body);

 通过@PartMap注解请求参数,如下:

@Multipart

@POST("banner/api/5item.json")

Observable<TestResponse> login(@PartMap Map<String, RequestBody> params);

上传文件使用方法如下:

示例为一个bid请求参数和2张图片

File file1 = new File(SDCardUtils.getSDCardPath() + "DCIM/100MEDIA/IMAG0009.jpg");

File file2 = new File(SDCardUtils.getSDCardPath() + "DCIM/100MEDIA/IMAG0010.jpg");

Map<String, RequestBody> map = new HashMap<>();

RequestBody bId = RequestBody.create(MediaType.parse("text/plain"), "1");

RequestBody imgFile1 = RequestBody.create(MediaType.parse("image/*"), file1);

RequestBody imgFile2 = RequestBody.create(MediaType.parse("image/*"), file2);

map.put("bId", bId);

map.put("headImage1\"; filename=\"" + file1.getName(), imgFile1);

map.put("headImage1\"; filename=\"" + file2.getName(), imgFile2);

注意:上传文件时map中key的格式必须是"headImage1\"; filename=\"" + file1.getName()。

1. headImage1:为参数key的名字

2. "; filename=\"" + file1.getName():为的文件的名字。

上传多张图片时,key的名字可以是相同的

 参考<四种常见的 POST 提交数据方式>:
http://www.cnblogs.com/aaronjs/p/4165049.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: