android - Retrofit Post json 遇到问题

 廖蓉以 发布于 2022-10-28 11:51

比如这样的接口
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.1
    11-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)
    2022-11-12 01:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有