I am having a problem executing a post request using Retrofit. I keep getting the Bad Request error log response.message()
This is the response from Postman GET request to my API:
{
"data": [
{
"id": 7,
"attributes": {
"createdAt": "2022-09-14T17:10:38.806Z",
"updatedAt": "2022-09-14T17:10:38.806Z",
"publishedAt": "2022-09-14T17:10:38.767Z",
"title": "This is title",
"body": "This is body"
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 1
}
}
}
I am able to perform the Retrofit GET and DELETE. The problem comes when am trying to execute a POST. This is the request body that is send using Postman and it is working correctly:
{
"data": {
"title": "This is title",
"body": "This is body"
}
}
How can I replicate this request body to make POST request using Retrofit using Android Java? Here is the code am using which is retuning Bad request error:
My interface:
public interface Service {
@FormUrlEncoded
@POST("api/notes")
Call<DataResponse> create(
@Field("title") String title,
@Field("body") String body
);
The method I am excuting to Post data:
private void create(){
//Call the interface
crudInterface = RestClient.connection().create(Service.class);
Call<DataResponse> call = crudInterface.create(title, body);
call.enqueue(new Callback<DataResponse>() {
@Override
public void onResponse(@NonNull Call<DataResponse> call, @NonNull Response<DataResponse> response) {
Toast toast = Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_LONG);
toast.show();
Log.e("Response : ", response.message());
Log.d("Response code: ", String.valueOf(response.code()));
}
@Override
public void onFailure(@NonNull Call<DataResponse> call, @NonNull Throwable t) {
Toast.makeText(getApplicationContext(), "Gagal menghubungi server : "+t.getMessage(), Toast.LENGTH_LONG).show();
Log.e("Throw err: ",t.getMessage());
}
});
}
I get this to my logcat:
2022-09-14 20:20:33.153 9649-9649/com.application.strapi_crud E/Response :: Bad Request
2022-09-14 20:20:33.252 9649-9649/com.application.strapi_crud D/Response code :: 400
Data class:
public class Data{
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Then:
public class Notes {
@SerializedName("id")
private int id;
@SerializedName("attributes")
private Data data;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Data getAttribute() {
return data;
}
public void setAttribute(Data attribute) {
this.data = data;
}
public void setAttribute(String title, String body) {
}
}
Finally the DataResponse:
public class DataResponse {
@SerializedName("data")
@Expose
private List<Notes> data = null;
public List<Notes> getData() {
return data;
}
public void setData(List<Notes> data) {
this.data = data;
}
}