android - Retrofit Post json 遇到问题

浏览:20日期:2022-11-18

问题描述

比如这样的接口http://www.xxx.com/xxx/xxx

post方式传

token='xxx' param='{user:{id:xxx,name:xxx},order:{id:xxx}}'

用retrofit 该怎么传?

我现在的方法表单形式上传

@Field('token') string token@Field('param') string param

问题解答

回答1:

将需要请求的数据定义成一个实体类

public class CustomBody { public String token; public User user; public Order order; public CustomBody(String token, User user, Order order) {this.token = token;this.user = user;this.order = order; } public static class Order {public String id;public Order(String id) { this.id = id;} } public static class User {public String id;public String name;public User(String id, String name) { this.id = id; this.name = name;} }}

Retrofit 的 Service 这样子写就可以了,使用 @Body 注解

public interface MyService { @POST('/') Observable<T> access(@Body CustomBody customBody);}

使用 HttpLoggingInterceptor 可以在 log 中查看 HTTP 请求的详细情况。

OkHttpClient.interceptors().add(new HttpLoggingInterceptor());

11-19 16:58:46.495 4591-4612/? D/OkHttp: --> POST / HTTP/1.111-19 16:58:46.495 4591-4612/? D/OkHttp: {'order':{'id':'1'},'token':'123','user':{'id':'1','name':'name'}}11-19 16:58:46.495 4591-4612/? D/OkHttp: --> END POST (66-byte body)

相关文章: