KTOR帖子总是返回错误
我一直在尝试在Kotlin Android应用程序中连接到Web API。我正在使用KTOR框架来执行此操作(2.0.1)。目前,获取请求似乎正在按预期工作,但是发布请求并不多。我不断收到400和500的错误,我不确定我在做什么错。我认为这与我如何设置身体数据有关。
这就是我初始化客户端的方式
client = HttpClient(Android) {
install(Logging) {
level = LogLevel.ALL
}
install(ContentNegotiation) {
json()
}
install(HttpTimeout) {
requestTimeoutMillis = 15000L
connectTimeoutMillis = 15000L
socketTimeoutMillis = 15000L
}
defaultRequest {
url("https://fakestoreapi.com/products")
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
}
,这就是我发送到发布请求(或至少是一种方式)的方式,
val sampleRequest: HttpResponse = client.request {
method = HttpMethod.Post
setBody("{\"title\": \"test product\", \"price\": \"13.5\", \"description\": \"lorem ipsum set\", \"image\": \"https://i.pravatar.cc\", \"category\": \"electronic\"}")
}
任何帮助都将受到赞赏。如果有人可以看一下样本,那也将很有帮助。提前致谢...
I've been trying to connect to a web API in my kotlin android application. I'm using the ktor framework to do this (2.0.1). For now, get requests appear to be working as expected, but post requests not so much. I keep getting 400 and 500 errors back and I'm not sure what I'm doing wrong. I think it has something to do with how I set the body data.
This is how I initialize the client
client = HttpClient(Android) {
install(Logging) {
level = LogLevel.ALL
}
install(ContentNegotiation) {
json()
}
install(HttpTimeout) {
requestTimeoutMillis = 15000L
connectTimeoutMillis = 15000L
socketTimeoutMillis = 15000L
}
defaultRequest {
url("https://fakestoreapi.com/products")
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
}
And this is how I send to post request (or at least, one of the ways)
val sampleRequest: HttpResponse = client.request {
method = HttpMethod.Post
setBody("{\"title\": \"test product\", \"price\": \"13.5\", \"description\": \"lorem ipsum set\", \"image\": \"https://i.pravatar.cc\", \"category\": \"electronic\"}")
}
Any help is appreciated. If anyone has a sample I can look at, that would be helpful as well. Thanks in advance...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论