【问题标题】:How to pass data in url without Query in Retrofit如何在没有查询的情况下在 URL 中传递数据
【发布时间】:2021-02-06 12:04:11
【问题描述】:

我正在使用 Retrofit 进行 API 调用。我的 API 是这样的 https://test/update/123456789..

在此 API 中,需要将“123456789”作为值传递。任何人都可以使用 Retrofit 帮助我做到这一点。如何在没有查询的情况下传递这个值。

在此先感谢..:)

fun updatePriceTesting(@Query("device_id") deviceId: String, @Query("appId") appId: String, @Body RequestBody: RequestBody) : Deferred

回应>

【问题讨论】:

  • @GET("/test/update/:id) fun whatever(@Path("id") id: Int) -- 请参阅the Retrofit docs 中的“URL 操作”部分。
  • @CommonsWare 好的,有时间我试试
  • 这将是这样的@GET("/yourUpdatePathThatWillBeAppendedToBaseUrl/{id}) fun update(@Path("id") id: Int) 您的请求类型可能是@POST 或@PUT 这取决于您的Api 实现
  • java.lang.NumberFormatException: For input string: "589656966" got this exception
  • @CommonsWare java.lang.IllegalArgumentException:URL 不包含“{id}”。 (参数#1)

标签: android kotlin mvvm retrofit


【解决方案1】:

要在改造中传递一个值,你必须将它注释为@Query,或@Path,如果你不想使用@Query,你可以在方法参数中使用@Path,例如:如果你想发送你的 api 的一个值,让我们说 www.fb.com/post,to通过帖子的ID来检索,我们必须这样做:

@Get("www.fb.com/post/{post_id}")

如果你的 id 是一个 int 那么你可以使用:

Call<Post> getPost( @Path("post_id") int postId);

但如果是字符串:

Call<Post> getPost( @Path("post_id") String postId);

然后你就可以调用这个方法了:

yourApiServiceObj.getPost(thePostId);

【讨论】:

  • 试过了,但得到了这样的错误“java.lang.IllegalArgumentException:URL不包含“{id}”。(参数#1)
  • 在您的 requestBody 或任何您的 url 中,只需输入 {id} 而不是 123456789
  • 当我像这样使用 id 意味着它会抛出错误 java.lang.IllegalArgumentException:URL 不包含“{id}”。 (参数#1)
【解决方案2】:

由于这似乎不清楚,我将其写为答案

如果您的网址是这样的update/123456789?appId=5452266update/device_id?appId=5452266,那么您的函数调用将是

@FormUrlEncoded
@POST("update/{device_id}")
fun updatePriceTesting(@Path("device_id") deviceId: String, @Field("appId") appId: String, @Body RequestBody: RequestBody) : Deferred

如果您的网址是这样的update/5452266?device_id=123456789update/appId?device_id=123456789,那么您的函数调用将是

@FormUrlEncoded
@POST("update/{appId}")
fun updatePriceTesting(@Field("device_id") deviceId: String, @Path("appId") appId: String, @Body RequestBody: RequestBody) : Deferred

如果你的网址是这样的update/123456789/5452266,也就是update/device_id/appId,那么你的函数调用将是

@FormUrlEncoded
@POST("update/{device_id}/{appId}")
fun updatePriceTesting(@Path("device_id") deviceId: String, @Path("appId") appId: String, @Body RequestBody: RequestBody) : Deferred

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 1970-01-01
    • 2022-12-22
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多