简体   繁体   中英

I tried to call a post request using PHP code, but I got 401 Unauthorized error.

I tried to send a post request using this PHP code but throw me 401 Unauthorized error:

$username = 'MyDomain\testuser';
$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\r\n",
                'content' => http_build_query($data)   
            )           
);

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

You're not doing proper basic auth. You have to build the authenticate header yourself:

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

You can't just shove a username/password elements into the array and expect it to work. PHP doesn't know you're building a stream to HTTP basic auth... you have to provide EVERYTHING yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM