【问题标题】:@POST request using Retrofit and Kotlin使用 Retrofit 和 Kotlin 的 @POST 请求
【发布时间】:2023-03-11 00:23:01
【问题描述】:

当我尝试使用 Postman 发布时,一切正常:

发布
https://trackapi.nutritionix.com/v2/natural/nutrients

标题

Content-Type : application/json
x-app-id : *******
x-app-key : *******
x-remote-user-id : 0

身体

{
"query":"carrot"
}

结果

{
"foods": [
    {
        "food_name": "carrot",
        "brand_name": null,
        "serving_qty": 1,
        "serving_unit": "carrot",
        "serving_weight_grams": 46,
        "nf_calories": 16.1,
        "nf_total_fat": 0.08, .........

但是,当我在我的应用程序中尝试这个时,我得到了空响应。 我尝试了 2 种不同的方法,但不幸的是没有结果。

第一:

@Headers(
    "Content-Type: application/json",
    "x-app-id: $NUTRITIONIX_APPLICATION_ID",
    "x-app-key: $NUTRITIONIX_API_KEY",
    "x-remote-user-id: 0",
)
@POST("v2/natural/nutrients")
suspend fun pushFoodNutrients(
    @Body query: String
): Response<FoodNutrientsResponse>

第二:

@FormUrlEncoded
@Headers(
    "Content-Type: application/json",
    "x-app-id: $NUTRITIONIX_APPLICATION_ID",
    "x-app-key: $NUTRITIONIX_API_KEY",
    "x-remote-user-id: 0",
)
@POST("v2/natural/nutrients")
suspend fun pushFoodNutrientsTest(
    @Field("query") query: String
): Response<FoodNutrientsResponse>

我的错误在哪里?我在互联网上搜索了一整天,但没有找到任何东西。

【问题讨论】:

    标签: kotlin post request retrofit httpresponse


    【解决方案1】:

    所以,我找到了解决方案。

    这是一个很好的,但有一个变化。

    @Headers(
    "Content-Type: application/json",
    "x-app-id: $NUTRITIONIX_APPLICATION_ID",
    "x-app-key: $NUTRITIONIX_API_KEY",
    "x-remote-user-id: 0",
    )
    @POST("v2/natural/nutrients")
    suspend fun pushFoodNutrients(
    @Body postModel: PostModel      // what I have changed
    ): Response<FoodNutrientsResponse>
    

    我用一个字段查询创建了一个对象 PostModel,如下所示:

    data class PostModel(
        val query: String
    )
    

    之后一切正常。

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 2017-05-30
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      相关资源
      最近更新 更多