PHP发布请求和unsupported_grant_type [英] PHP post request and unsupported_grant_type

查看:187
本文介绍了PHP发布请求和unsupported_grant_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

$data = array(
        'grant_type'  => 'Password',
        'username'    => 'username',
        'password'    => 'pwd',
        'DeviceId'    => ''
    );


    $url = "http://test/sync/oauth/token";    

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ( $status != 201 ) {
        die("Error: call to URL $url failed with status $status, response $response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
    }


    curl_close($curl);

    print_r($response);`

我认为是正确的,但是服务器向我返回此错误

I think is correct, but the server return me this error

错误:对URL http://test/sync/oauth/token 的调用失败,状态为 400,响应{"error":"unsupported_grant_type"},curl_error, curl_errno 0

Error: call to URL http://test/sync/oauth/token failed with status 400, response {"error":"unsupported_grant_type"}, curl_error , curl_errno 0

错误在哪里?

推荐答案

好吧,所以我浪费了几个小时并进行了大量测试 我想出了一个解决方案,希望对您的案件有帮助

Ok so after wasting my couple of hours and doing tons of testing I came up with a solution and hope it helps with your case

Tip : Dont Concatenate the Post Arguments into a string and add it in Array just use it sepratlely so with that you dont even need to add the Custom_HEADERS => Content-Type : application/x-www-form-urlencoded

有人说您需要将application/x-www-form-urlencoded添加为Content-Type,这样就可以了,但是我的解决方案可以正常工作 继承人的工作代码

Some people says that you need to add application/x-www-form-urlencoded as Content-Type then it would work but my solution works perfectly heres the working code

$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);  
curl_setopt($curl, CURLOPT_URL, 'YOUR_TOKEN_URL_HERE');
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
 'Username' => 'YOUR_USERNAME',
 'Password' => 'YOUR_PASSWORD',
 'grant_type' => 'password'
)));
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
echo $result;

此代码也非常适合Laravel Bearer令牌和其他代码

This code works perfectly for Laravel Bearer Token and others too

参考资料: CURL POST格式

希望您的情况对我的回答有所帮助 快乐编码:)!

Hope my answer help in your Situation Happy Coding :) !

这篇关于PHP发布请求和unsupported_grant_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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