Guzzle 3.x 如何设置内容类型:application/json?

我使用的是旧的 php 版本,所以我无法在当前服务器上更新 guzzle。


有办法吗set Content-Type :application/json?


我在本地机器上使用的代码(我尝试了不同的方法来设置 Content-Type - 它被注释掉了):


    $client = new \Guzzle\Http\Client();

    $request = $client->post($cms_admin_api_url,

        ['headers' => [

            'user-agent' => $admin_token,

            //'Content-Type' => 'application/json',

            //'Accept' => 'application/json'

        ],

        //'Content-Type' => 'application/json'

        ],

        ['json'        => [

            'name' => $key,

            'image' => base64_encode($body),

            'env' => $cake_emv

        ]

        ]);

        $response = $request->send();

我收到这样的回复:


POST /api/image/xxx HTTP/1.1

Content-Length:    88

Content-Type:      application/x-www-form-urlencoded; charset=utf-8

Headers:           A7t1xXXXXXXXr23vt8jL999

Host:              my_api.url.com

User-Agent:        Guzzle/3.9.3 curl/7.19.7 PHP/5.6.30

X-Amzn-Trace-Id:   Root=1-5ec66539-XXXXXXXXX9c3c667a3a

X-Forwarded-For:   118.XXXX.242

X-Forwarded-Port:  443

X-Forwarded-Proto: https


json%5Bname%5D=article%2Fartem%2Ftest77.jpg&json%5Bimage%5D=eHh4&json%5Benv%5D=localhost

我想得到这样的回应:


POST /api/image/xxx HTTP/1.1

Content-Length:    70

Content-Type:      application/json

Host:              my_api.url.com

User-Agent:        A7t1xXXXXXXXr23vt8jL999

X-Amzn-Trace-Id:   Root=1-5ec66539-XXXXXXXXX9c3c667a3a

X-Forwarded-For:   118.XXXX.242

X-Forwarded-Port:  443

X-Forwarded-Proto: https


{"name":"article\/artem\/test77.jpg","image":"eHh4","env":"localhost"}


米琪卡哇伊
浏览 187回答 1
1回答

智慧大石

setBody()成功了:$client = new \Guzzle\Http\Client();$client->setUserAgent($admin_token);$request = $client->post($cms_admin_api_url);$request->setBody(json_encode([    'name'  => $key,    'image' => base64_encode($data)]), 'application/json');$response = $request->send();
打开App,查看更多内容
随时随地看视频慕课网APP