我正在向 API 提交 CURL Post 请求,该请求成功后会返回状态“201 Created”,并在LOCATION标头部分中包含资源的 URL。我想要的是自动检索新创建的资源,但到目前为止还无法做到这一点。我尝试过设置curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);但没有效果。值得注意的是,该资源确实需要请求GET。
我不确定状态代码是否为 201,或者请求方法是否需要从 更改POST为GET,但由于某种原因它没有遵循LOCATION标头。获取curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);似乎证实了这一点,因为结果与原始 URL 相同,而不是新的LOCATION.
作为最后的手段,我考虑过简单地解析标头并创建一个新的 CURL 请求,但这不是最佳选择,我猜我只是缺少一些简单的东西来使这项工作按预期工作。
如何让 CURL 自动跟踪并向返回者提交请求GET并返回LOCATION201 响应?
你不能。
使用curl只curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);遵循状态代码的响应。LOCATION3xx
AFAIK 并在文档中指出,没有办法通过 201 响应强制curl 到后续位置。
您必须解析标头,获取 LOCATION,然后发出第二个curl 请求。
跟踪状态与此不同的位置3xx将被视为异常。还来自curl命令行工具和C库文档:-L, --location -- (HTTP) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place
快速浏览一下您在/lib/http.c该函数上找到的curl 源代码Curl_http_readwrite_headers。
位置跟随在内部用这个条件处理:
else if((k->httpcode >= 300 && k->httpcode < 400) &&
checkprefix("Location:", k->p) &&
!data->req.location) {
/* this is the URL that the server advises us to use instead */
char *location = Curl_copy_header_value(k->p);
if(!location)
return CURLE_OUT_OF_MEMORY;
if(!*location)
/* ignore empty data */
free(location);
else {
data->req.location = location;
if(data->set.http_follow_location) {
DEBUGASSERT(!data->req.newurl);
data->req.newurl = strdup(data->req.location); /* clone */
if(!data->req.newurl)
return CURLE_OUT_OF_MEMORY;
/* some cases of POST and PUT etc needs to rewind the data
stream at this point */
result = http_perhapsrewind(conn);
if(result)
return result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
该位置后面是300和之间的状态代码399
| 归档时间: |
|
| 查看次数: |
2131 次 |
| 最近记录: |