关于Web服务:PHP cURL请求返回401,但可与Postman一起使用

PHP cURL request return 401, but works with Postman

如果我使用以下参数用Postman执行Webservice调用:

1
2
3
Content-Type: application/json
Cookie: xxxx
Body: json

Web服务成功返回JSON。

因此,我用邮递员生成了代码并将其粘贴到PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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上执行该服务时,它正在工作。
我和邮递员有什么不同?


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"

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

通常可以通过模拟Web请求来解决此问题

例如:-

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

然后您将有两个请求应该执行

1-发布一些登录身份验证数据
2-将第一个请求返回的cookie发送到第二个请求标头

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

特别是CURLOPT_COOKIEJAR , CURLOPT_COOKIEJAR and CURLOPT_COOKIE选项


我有一个类似的问题。在邮递员那里,它正在工作,但是通过卷曲它给出了401错误。

现在它对我有用,下面的代码。我已经使用base64_encode作为用户名和密码。

手册页参考:https://www.php.net/manual/zh/function.curl-setopt.php

1
2
3
4
5
6
7
8
9
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic".base64_encode($username.":".$password), ]);  
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
echo"<br/>http status code is".$status_code;

输出:

1
http status code is 200