我正在尝试使用Retrofit发送post请求,但服务器响应错误400:错误请求。
BASEURL:http://taskdemoserver.pythonanywhere.com
这是服务器文档的屏幕截图。
这是改造界面。
package com.e.databaseapp
import retrofit2.Call
import retrofit2.http.*
interface Service {
@Headers("user: joan","Content-Type: application/json")
@GET( "task" )
fun getListTask() : Call<TaskListContainer>
@Headers("user: joan","Content-Type: application/json")
@POST("task")
fun saveTask (@Body task: Task) : Call<Task>
@Headers("user: joan")
@DELETE("task")
fun deleteTask (task: String) : Call<Void>
}
我在我的存储库中创建了一个Retrofit实例。
lass TaskRepository(val taskDao: TaskDao) {
val gson : Gson = GsonBuilder()
.setLenient()
.create()
val loggingInterceptor : HttpLoggingInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
val httpClient : OkHttpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("http://taskdemoserver.pythonanywhere.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.build()
val service: Service = retrofit.create(Service::class.java)
...
}
这是我尝试发布任务时遇到的错误。
你可能遇到这些问题:
1)服务器无法定义响应的内容。尝试添加内容类型为:@Headers("Content-Type: application/json")
的标头
2)你的基本网址最后缺少/
斜线。
基本URL应始终以/结尾
改变.baseUrl("http://taskdemoserver.pythonanywhere.com")
in
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("http://taskdemoserver.pythonanywhere.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.build()
到.baseUrl("http://taskdemoserver.pythonanywhere.com/")
即使我不是100%确定这是否是您的问题,因为您上传的服务器文档不完整,我相信问题是服务器要求您发送要创建的任务的数据使用mime类型application/x-www-form-urlencoded
,这就是为什么它在您使用服务器文档上传的图片中将formdata
放在Create Task endopoint右侧。
但是,您正在使用@Body tasks: TaskListContainer
,而是将新任务的信息作为JSON数据application/json
发送。 (@Body annotation)
我使用Postman作为您的请求的内容类型,使用application/json
测试了您的终端。这就是Retrofit现在正在做的事情,因为您在Retrofit服务中使用了@Body
注释。
现在,如果我使用Postman发送POST请求但是使用form-data
类型,使用带有密钥task
的字段和表示要创建的任务名称的String值,我得到一个成功的响应。
要告诉Retrofit像这样发送POST请求,你必须像这样定义你的saveTask
方法:
interface Service {
...
@Headers("user: joan")
@FormUrlEncoded
@POST("task")
fun saveTask (@Field("task") taskname: String) : Call<Task>
...
}
您可以在the official documentation中查看有关@FormUrlEncoded注释的更多信息。
另外,正如@YuriPopiv所说,你错过了baseUrl
的最后一个斜线。尝试将其设置为像.baseUrl("http://taskdemoserver.pythonanywhere.com/")
或从领先的/
开始定义您的端点。
来自the docs:
基本URL应始终以/结尾。尾随/确保作为相对路径的端点值将正确地附加到具有路径组件的基础。