我正在使用browserstack屏幕截图API - https://www.browserstack.com/screenshots/api以下卷曲正在运行:
curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"browsers": [{"os": "Windows", "os_version": "7", "browser_version": "8.0", "browser": "ie"}], "url": "http://google.com"}' http://www.browserstack.com/screenshots
但是,当我用guzzle尝试相同的调用时,我得到422 Unprocessable Entity错误。
$client = new GuzzleHttp\Client();
$request = $client->post('http://www.browserstack.com/screenshots', [
'headers' => ['Content-type' => 'application/json'],
'auth' => ['username', 'password']
]
);
$data = ['browsers' => ['os' => 'Windows', 'os_version' => '7', 'browser_version' => '8.0', 'browser' => 'ie'], 'url' => 'http://google.com'];
$request->setBody($data);
$response = $request->send();
dd($response);
您能否建议如何调试此问题?
答案 0 :(得分:2)
要将JSON发送到Screenshots API,您需要将其格式化为JSON字符串。
$client = new GuzzleHttp\Client();
$request = $client->post('http://www.browserstack.com/screenshots', [
'headers' => ['Content-type' => 'application/json'],
'auth' => ['username', 'access_key'],
'body' => '{"browsers": [
{"os": "Windows", "os_version": "7", "browser_version": "8.0", "browser": "ie"},
{"os": "android", "os_version": "4.4", "device": "HTC One M8", "browser": "Android Browser"}
],
"url": "http://www.lipsum.com"}'
]
);
然后,您就可以在BrowserStack Screenshots页面上查看进度。
有关如何使用Guzzle发送POST请求的指南,您可以参考此文档 - https://media.readthedocs.org/pdf/guzzle/latest/guzzle.pdf。
答案 1 :(得分:2)
我的方法有误。它应该是$client->createRequest
而不是$client->post
另外,我传递的数据有误。浏览器应该是数组数组
还有另一个可以与browserstack和guzzle一起使用的库:https://github.com/ksenzee/browserstack-screenshots-php
$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'http://www.browserstack.com/screenshots', [
'headers' => ['Content-type' => 'application/json'],
'auth' => ['user', 'pwd'],
'body' => '{"browsers": [
{"os": "Windows", "os_version": "7", "browser_version": "8.0", "browser": "ie"},
{"os": "android", "os_version": "4.4", "device": "HTC One M8", "browser": "Android Browser"}
],
"url": "http://www.lipsum.com"}'
]
);
$response = $client->send($request);
dd($response->json());
答案 2 :(得分:0)
在我的情况下,在选项的参数(https://es.stackoverflow.com/questions/185183/porqu%C3%A9-guzzle-5-0-lanza-el-error-422-si-estoy-armando-bien-la-consulta#185192)中使用'json',例如:
$client = new GuzzleHttp\Client(['base_url' => 'http://www.browserstack.com/']);
$request = $client->post('screenshots', [
'headers' => ['Content-type' => 'application/json'],
'auth' => ['username', 'access_key'],
'json' => '{"browsers": [
{"os": "Windows", "os_version": "7", "browser_version": "8.0", "browser": "ie"},
{"os": "android", "os_version": "4.4", "device": "HTC One M8", "browser": "Android Browser"}
],
"url": "http://www.lipsum.com"}'
]
);