【问题标题】:Retrofit posts empty data改造发布空数据
【发布时间】:2018-06-03 10:53:31
【问题描述】:

我是 Retrofit 的新手。 我只是使用改造向我的数据库添加一行,但我在我的 api 界面中使用了字段参数,就像这样。

Call<String> matchWith(@Field("fbid") String fbid, @Field("matchwith") String matchwith);

很难为大对象编写,所以我决定使用@Body 注释。但现在它在我的 mysql 数据库中发布空行/对象。 (使用 api 接口中的@Field 注释我的代码正确插入数据)

这是我的代码

@POST("/insertuser.php")
Call<User> postUser(@Body User user);



Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://myurl.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    Connect connect = retrofit.create(Connect.class);

    Call<User> call = connect.postUser(user);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {

        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {

        }
    });

在我的对象类中,我使用了 @SerializedName@Expose 改造仍然插入空我尝试过仅使用 @SerilizedName 并仅使用 @Expose 之后我什么也没使用,但我得到了相同的结果。

【问题讨论】:

  • 会不会是'user'是空的?
  • 没有用户对象不为空。

标签: android gson retrofit retrofit2


【解决方案1】:

@Field@Body 注释之间存在差异。您的 API 可能仅接受 form-data 形式的数据。这就是为什么当您通过请求正文(即使用 @Body 注释)发送数据时,您的数据被视为空数据。

您可以更改您的 Web API 以接受数据作为请求正文,然后按您的使用方式使用。

More info

【讨论】:

  • 我更新了接受正文的 api。现在我可以插入我的数据了,谢谢。
  • Emre Akcan,我试着理解,但我不能......“更新接受身体的api”到底是什么意思?
【解决方案2】:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient=new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);**


        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();
        }

现在你可以看看你是否正确发送了正确的数据和服务器响应,否则在服务器中搜索问题

【讨论】:

  • 没有像 addInterceptor 这样的方法我应该在哪里添加这个方法? retrofit.addInterceptor 不可接受
  • 您可以在 OkHttp 客户端中添加该拦截器。
  • 谢谢,但我发送的请求是正确的,问题是我的 api 不接受正文。它在上面的答案中有解释。
猜你喜欢
  • 1970-01-01
  • 2017-07-15
  • 2019-06-14
  • 2021-04-02
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
相关资源
最近更新 更多