我遇到@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);
CommentDTO
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,就像我在邮递员请求中一样?
答案 0 :(得分:0)
在您的端点类中添加Headers行可能会成功:
[0]
并且不要忘记在网络请求方法中添加HttpLoggingInterceptor,因为添加HttpLoggingInterceptor可以看到您的应用程序发送到服务器的内容。