我试图使用PHP代码调用POST请求,但收到了401个未经授权的错误。 [英] I tried to call a post request using PHP code, but I got 401 Unauthorized error.

查看:0
本文介绍了我试图使用PHP代码调用POST请求,但收到了401个未经授权的错误。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此PHP代码发送POST请求,但抛出401未经授权的错误:

$username = 'MyDomain	estuser';
$password = '123456';
$url = 'http://10.20.30.40:8080/TargetPage.aspx';

$data = array(
         'username' => $username,
         'password' => $password, 
         'postdata' => 'InputParameter1=Test1&InputParameter2=Test2'
);

$options = array(    
    'http' => array
            (
                'method'  => 'POST',
                'header'  => "Content-type: application/x-www-form-urlencoded
",
                'content' => http_build_query($data)   
            )           
);

$context  = stream_context_create($options);    
$result = file_get_contents($url, false, $context);

推荐答案

您没有执行正确的基本身份验证。您必须自己构建身份验证标头:

$options = array(
    'http' => array(
        'header' => 'Authorization: Basic ' . base64_encode("$username:$password")
    )
);

您不能简单地将用户名/密码元素放入数组并期望它工作。PHP不知道您正在构建一个指向HTTP基本身份验证的流...你必须自己提供一切。

这篇关于我试图使用PHP代码调用POST请求,但收到了401个未经授权的错误。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆