icelic
icelic

Reputation: 113

How to send request body in retrofit call?

I have this call defined in service class

@POST("enquiries/")
Call<Enquiry> postEnquiry(
        @Header("Authorization") String token,
        @Body RequestBody body
);

and this when I actually call it in my repository file:

RequestBody body = requestBody.build();
    enquiriesService.postEnquiry(token, body).enqueue(new Callback<Enquiry>() {...

When inspecting outgoing network calls I found out that body of the outgoing request is empty.

How to I send RequestBody object in request body?

Upvotes: 1

Views: 2554

Answers (2)

mixin27
mixin27

Reputation: 159

You can use Model class to send body of your request.

For example,

// Task.java
public class Task {  
    private long id;
    private String text;

    public Task(long id, String text) {
        this.id = id;
        this.text = text;
    }
}

// ApiInterface
public interface TaskApi {  
    @POST("/tasks")
    void createTask(@Body Task task);
}

// You can request like this
Task task = new Task(1, "my task title");  
Call<Task> call = taskService.createTask(task);  
call.enqueue(new Callback<Task>() {});  

So, your request body look like this

{
    "id": 1,
    "text": "my task title"
}

Upvotes: 0

truthsayer
truthsayer

Reputation: 429

What do you mean by send? Your code already sends a Request body and the token.

You can always use HttpLoggingInterceptor to Log your request in the Logcat https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

val apiService: ApiService
        get() = setupInstance().create(ApiService::class.java)

private fun setupInstance(): Retrofit {

        return Retrofit.Builder()
                .baseUrl("BASE_URL")
                .client(createClient())
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
}

private fun createClient(): OkHttpClient {
        val logging = HttpLoggingInterceptor()
        HttpLoggingInterceptor.Level.BODY

        return OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()
}

Upvotes: 1

Related Questions