我在服务类中定义了此调用
@POST("enquiries/")
Call<Enquiry> postEnquiry(
@Header("Authorization") String token,
@Body RequestBody body
);
这是我在存储库文件中实际调用它时的情况:
RequestBody body = requestBody.build();
enquiriesService.postEnquiry(token, body).enqueue(new Callback<Enquiry>() {...
在检查传出网络呼叫时,我发现传出请求的正文为空。
如何在请求正文中发送RequestBody对象?
答案 0 :(得分:1)
发送是什么意思?您的代码已经发送了一个请求正文和令牌。
您始终可以使用HttpLoggingInterceptor在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()
}
答案 1 :(得分:0)
您可以使用Model
类发送请求的正文。
例如,
// 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>() {});
因此,您的请求正文如下
{
"id": 1,
"text": "my task title"
}