php - 将 curl 示例转换为 Requests util 用法

标签 php http curl

我使用 Requests对于 http 请求:

我也打包成一个util函数:

function http_util($url, $params, $add_headers = null, $base_url = null ){

    $headers = array('Accept'=>'application/json');

    if($add_headers){
        $headers = array_merge($headers, $add_headers);
    }

    if($base_url) {
        $url = $base_url . $url;
    }

    $request = Requests::post($url, $headers, $params);

    return $request;
}

但是我发现,比如curl的例子:

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/

如果 curl 示例转换为使用我的 http_util,如何使用?我不确定我的 http_util 是否会有更多优化操作。以及如何使用 http_util 请求 curl 示例?

最佳答案

您不能按原样使用它,您需要添加 $options 参数,如文档中所述:http://requests.ryanmccue.info/docs/authentication.html

“util”函数只是设置一个内容 Accept header 。不值得为此编写函数。

$result = Requests::post('http://localhost:8000/o/token' [
    // headers
    'Accept' => 'application/json'
 ], [
    // data
    'grant_type' => 'password',
    'username' => '<user_name>',
    'password' => '<password>',
], [
    // options
    'auth' => new Requests_Auth_Basic(['<client_id>', '<client_secret>'])
]);

关于php - 将 curl 示例转换为 Requests util 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51397128/

相关文章:

php - 带有 LIMIT 的线索评论

PHP-编辑记录

http - 页面在解析时返回不同的内容

python-3.x - 某些 'utf-8'编解码器无法解码字节

php - 限制 Laravel 5 加密长度

php - 将 Symfony 1.4 sfGuardUser 表与 Symfony 2 SecurityBundle 一起使用?

wcf - IFrame 回调,服务器响应未出现在客户端上

http - URL 可以有星号吗?

shell - 变量没有在 jenkins 管道的 sh 中填充

rest - 来自 curl 的跨源调用在不需要 header 的情况下工作