【问题标题】:Retrofit post request sends null object改造后请求发送空对象
【发布时间】:2018-11-13 05:30:03
【问题描述】:

@POST 改造请求有问题,每当我尝试从 android 应用程序发送对象时,它基本上发送 null,但是当我从 Postman 发送时,一切正常。

这是我发送的邮递员请求

Address: http://localhost/posts/1/comments/3
{
"title": "Bravo nasiasfaf",
"description": "Samo sloga Srbina spasavaasfsaf"
}

这里是端点的方法

@POST("posts/{postId}/comments/{userId}")
Call<CommentDTO> createComment(@Path("postId") int postId, @Path("userId") int userId, @Body CommentDTO commentDTO);

评论DTO

public class CommentDTO {

private String title;
private  String description;

public CommentDTO(String title, String description) {
    this.title = title;
    this.description = description;

}
}

具有呼叫监听器的按钮

    final EditText naslov_comm = view.findViewById(R.id.naslov_comm);
    final EditText opis_comm = view.findViewById(R.id.opis_comm);
    objavicom_btn = view.findViewById(R.id.objavicom_btn);

objavicom_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        CommentDTO commentDTO_ala = new CommentDTO(naslov_comm.getText().toString(),
                opis_comm.getText().toString());

        sendNetworkRequest(commentDTO_ala);

        }


    });

来自按钮监听器的网络请求方法

private void sendNetworkRequest(CommentDTO commentDTO) {

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();

    RestAPI client = retrofit.create(RestAPI.class);

    Call<CommentDTO> call = client.createComment(id_post, user_pref, commentDTO);

    call.enqueue(new Callback<CommentDTO>() {
        @Override
        public void onResponse(Call<CommentDTO> call, Response<CommentDTO> response) {
            Toast.makeText(getActivity(), "Uspesno ste objavili komentar",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onFailure(Call<CommentDTO> call, Throwable t) {
            Toast.makeText(getActivity(), "Komentar nije prosao",
                    Toast.LENGTH_LONG).show();
        }
    });

我如何使改造和 gson 创建与我在邮递员请求中输入的相同形式的 JSON?

【问题讨论】:

    标签: java android post retrofit


    【解决方案1】:

    也许在您的端点类中添加 Headers 行会成功:

    @Headers("Content-Type: application/json")
    @POST("posts/{postId}/comments/{userId}") 
    Call<CommentDTO> createComment(@Path("postId") int postId, @Path("userId") int userId, @Body CommentDTO commentDTO);
    

    并且不要忘记在您的网络请求方法中添加 HttpLoggingInterceptor,因为添加 HttpLoggingInterceptor 您可以看到您的应用发送到服务器的内容。

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2020-03-15
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多