gpt4 book ai didi

android - 如何从请求正文中需要字段的 api 端点获取 Retrofit 调用的 HEAD?

转载 作者:可可西里 更新时间:2023-11-01 17:06:34 29 4
gpt4 key购买 nike

在实际下载内容之前,我正在尝试检查通过 Retrofit 2.0.2 进行的 API 调用的响应 header 。

我的 API 接口(interface)如下所示:

@Headers({"Accept: application/json", "Origin: http://www.example.com"})
@HEAD("profiles")
Call<Void> getProfileHeaders(@Field("puids") String puid);

请注意,API 调用要求我在正文中指定一个名为 puids=%{UUID} 的 UUID 列表字段,以便返回响应。

如果我想在不先检查标题的情况下下载数据,我会调用这样的接口(interface):

@Headers({"Accept: application/json", "Origin: http://www.example.com"})
@FormUrlEncoded
@POST("profiles")
Call<String> getProfile(@Field("puids") String puid);

现在的问题是,当我尝试使用 getProfileHeader() 端点时,我得到以下 RuntimeException:

java.lang.IllegalArgumentException: @Field parameters can only be used with form encoding. (parameter #1)

为了使用@Field 参数(我想如果需要,POST 方法通常会这样做),我必须明确指定我使用@FormUrlEncoded,但我不能用它进行 @HEAD 调用。

我有点困惑,我怎么能达到我想要的,我错过了什么?

基本上,我想知道如何在下载需要字段参数的 API 端点的实际主体之前检查改造调用的响应 header ?

干杯!

最佳答案

好吧,我刚刚意识到我的困惑源于几个误解:

  1. @HEAD 是一种 HTTP 方法,通常用于验证超链接的有效性和服务器对 GET 调用的响应。它不适用于 POST 请求,理论上是不正确的。

取自 RFC2616 的 HTTP/1.1 定义:

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

  1. 根据定义发出 POST 请求时,我们已经计算了服务器端的响应,并花时间下载了考虑中的正文。

RFC2616 中定义的 POST 方法的功能之一是:

  • Providing a block of data, such as the result of submitting a form, to a data-handling process;

因此,为了不下载正文而验证 header 超出了此目的。


正如上面@Radek 所提到的,在 GET 请求上使用拦截器来动态修改和/或检查请求可以完成这项工作,但此时我们也可以启动 HEAD 方法请求。

这个问题的解决方案是通过在服务器端进行更改而不是将原始数据 block 作为 POST 响应返回,从而更好地与 RFC2616 中定义的标准定义保持一致,让它返回一个资源,然后在 GET/HEAD 请求中调用。所有这些都只是重构服务调用以使用 GET 而不是 POST

关于android - 如何从请求正文中需要字段的 api 端点获取 Retrofit 调用的 HEAD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829150/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com