gpt4 book ai didi

PHP cURL 请求返​​回 401,但适用于 Postman

转载 作者:行者123 更新时间:2023-12-04 17:53:25 24 4
gpt4 key购买 nike

如果我使用带有这些参数的 Postman 执行 Web 服务调用:

Content-Type: application/json
Cookie: xxxx
Body: json

Webservice 成功返回一个 JSON。

因此,我使用 Postman 生成代码并将其粘贴到 PHP 上:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "json",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
"cookie: xxxx",
"postman-token: 7c771f8e-5c87-1d27-64f3-bdb92bba6a19"
),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

并且 Web 服务返回错误 401。但是当我在 Postman 上执行它时它正在工作。我和 Postman 有什么不同?

最佳答案

401 错误代码通常是因为某些授权问题:-

401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication"

这意味着您在验证您的请求时遇到问题

通常这会通过模拟网络请求来解决

例如:-

假设您有一些需要登录才能访问的页面,

那么你将有两个你应该做的请求

1-发布一些登录认证数据2- 将从第一个请求返回的 cookie 发送到第二个请求 header

您需要在 cURL 中阅读有关 cookie 的更多信息在 php 手册页中

特别是 CURLOPT_COOKIEJAR、CURLOPT_COOKIEJAR 和 CURLOPT_COOKIE 选项

关于PHP cURL 请求返​​回 401,但适用于 Postman,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460771/

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