如何使用标头对API进行HTTP POST请求 [英] How to make a HTTP POSTrequest to an API using headers
问题描述
我需要将API集成到我的应用中。
文档说:
I need to integrate an API into my app. The docs say:
HTTP POST
以下是HTTP POST请求和响应的示例。显示的占位符需要替换为实际值。
POST /partnerhubwebservice.asmx/Authorise HTTP/1.1
Host: stage.example.co.uk
Content-Type: application/x-www-form-urlencoded
Content-Length: length
username=string&password=string
并且回复是:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<AuthorisationResult xmlns="http://webservice.example.co.uk/">
<Token>string</Token>
</AuthorisationResult>
阅读文档我在Laravel Controller中创建了这个函数:
Reading the docs I create this function in Laravel Controller:
public function testRld() {
$client = new GuzzleHttp\Client();
try {
$res = $client->post('http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'x-www-form-urlencoded' => [
'Username' => 'MMM_bookings',
'Password' => 'passwordaaaa',
]
]);
return $res;
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
但我得到了消息:
RequestException.php第111行中的ServerException:服务器错误:
POST
http:/ /stage.example.co.uk/partnerhubwebservice.asmx/Authorise
导致500内部服务器错误
响应:缺少参数:
用户名。
ServerException in RequestException.php line 111: Server error:
POST http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise
resulted in a500 Internal Server Error
response: Missing parameter: username.
当我在POSTMAN应用程序中尝试此操作时,一切都很好,我得到了响应ike:
When I try this at POSTMAN app everything is fine and there I get response ike:
<?xml version="1.0" encoding="utf-8"?>
<AuthorisationResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://webservice.example.co.uk/">
<RequestSuccessful>true</RequestSuccessful>
<ErrorMessage />
<Token>27d67d31-999-44e0-9851-d6f427fd2181</Token>
</AuthorisationResult>
请帮我解决这个问题?我的代码出了什么问题?为什么我收到错误,并且POSTMAN请求正常...
Please help me to solve this problem? What is wrong with my code? WHy I got the error , and POSTMAN request works fine ...
推荐答案
尝试在正文中发送用户名和密码正文
或 json
,而不是 application / x-www-form-urlencoded
,如下:
Try sending username and password inside of a body as body
or json
, instead of as application/x-www-form-urlencoded
, like so:
$res = $client->post('http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'json' => [
'username' => 'MMM_bookings',
'password' => 'passwordaaaa',
]
]);
或
$res = $client->post('http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'body' => [
'username' => 'MMM_bookings',
'password' => 'passwordaaaa',
]
]);
这篇关于如何使用标头对API进行HTTP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!