【问题标题】:GuzzleHttp Client - post random form dataGuzzleHttp 客户端 - 发布随机表单数据
【发布时间】:2017-01-30 14:59:27
【问题描述】:

让我们从例子开始。

如果我有固定的表单参数(姓名、电子邮件、电话),那么 Guzzle Post 方法代码将是这样的:

public function test(Request $request){
$client = new \GuzzleHttp\Client();

    $url = www.example.com

    $res = $client->post($url.'/article',[
        'headers' => ['Content-Type' => 'multipart/form-data'],
        'body' => json_encode([
            'name' => $request['name'],
            'email' => $request['email'],
            'write_article' => $request['article'],
            'phone' => $request['phone'],
        ])
    ]);
}

以上代码运行良好。

但是当没有固定的表单参数时,如何使用 Guzzle 发送数据?

我第一次提交表单时的例子,我有 name , email , phone 字段。下一次可能是 name、email、phone、father_name、mother_name、interest 等字段。。下次可能是 姓名、电子邮件、父亲姓名

那么如何处理这种动态表单域的情况呢?

【问题讨论】:

    标签: php httpclient guzzle


    【解决方案1】:

    试试这个:

    public function test(Request $request)
    {
        $client = new \GuzzleHttp\Client();
        $url = 'www.example.com';
    
        $body = [];
    
        // exceptions, for when you want to rename something
        $exceptions = [
            'article' => 'write_article',
        ];
    
        foreach ($request as $key => $value) {
            if (isset($exceptions[$key])) {
                $body[$exceptions[$key]] = $value;
            } else {
                $body[$key] = $value;
            }
        }
    
        $res = $client->post($url.'/article',[
            'headers' => ['Content-Type' => 'multipart/form-data'],
            'body' => json_encode($body)
        ]);
    }
    

    【讨论】:

    • 另一端我的意思是 /article 路由端如何获取 body 参数?我在那一边尝试了 print_r($request) 但什么也得不到。有什么想法吗?
    • 你怎么看?
    • 如果我将 $body[name] = john; 从 guzzle 传递到 /article 路线,那么如何获得 name=jone 在 /article 一侧?
    • 这在很大程度上取决于您的框架,但一种方法是查看$_POST 超全局。
    • 我用的是laravel php框架,代码是这样的:** public function article(Request $request){ return $request; } ** 但请求数组不给我名称参数。你能帮帮我吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2012-06-24
    • 1970-01-01
    • 2017-03-09
    • 2016-09-20
    相关资源
    最近更新 更多