我正在尝试使用改进2向我的WebAPI发出POST请求以在请求体中传递数据,但它通过了EMPTY Body for API。然后API返回一个BAD REQUEST 400 CODE。
这是我的服务界面。
public interface MyClient {
@POST("feedbacks")
Call<Feedback> sendFeedback(@Body Feedback feedback);
}
这是我的反馈课程。
public class Feedback {
@SerializedName("Feedback_ID")
@Expose
private Integer Feedback_ID;
@SerializedName("Feed")
@Expose
private String Feed;
public Feedback(String feed) {
Feed = feed;
}
public Integer getFeedback_ID() {
return Feedback_ID;
}
}
我在按钮点击事件中发出请求。
public void onClick(View view) {
if (view == sendButton) {
if (!feedbackEditText.getText().toString().isEmpty()) {
Feedback feedback = new Feedback(
feedbackEditText.getText().toString()
);
sendFeedback(feedback);
} else {
Toast.makeText(ActivityFeedBack.this, getResources().getString(R.string.activity_feedback_feedbackFieldIsEmpty), Toast.LENGTH_LONG).show();
}
}
}
最后这是我的请求方法
private void sendFeedback(Feedback feedback) {
progressBar.setVisibility(View.VISIBLE);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
MyClient myClient = retrofit.create(MyClient.class);
Call<Feedback> call = myClient.sendFeedback(feedback);
call.enqueue(new Callback<Feedback>() {
@Override
public void onResponse(Call<Feedback> call, Response<Feedback> response) {
progressBar.setVisibility(View.GONE);
if (response.isSuccessful()) {
Toast.makeText(activity, "DONE", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(activity, response.message(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Feedback> call, Throwable t) {
progressBar.setVisibility(View.GONE);
Toast.makeText(activity, call.toString(), Toast.LENGTH_LONG).show();
}
});
}
所有帮助将不胜感激。谢谢。
答案 0 :(得分:0)
我认为这种情况正在发生,因为正在使用@Expose注释,尝试将它们从您的请求体类中删除或在您的gson上添加它:
private Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
我希望它可以帮到你。