如何使用Guzzle向只支持XML格式的Restful发送API请求?

问题描述 投票:0回答:1

我一直在Laravel 5.8项目中使用Guzzle一段时间。它一直在使用支持JSON格式的Restful API。

现在有一个新的Restful API只支持XML格式。我不知道如何使用Guzzle做到这一点。下面是HTTP请求的外观示例。

POST: http://api.url_endpoint.com/my_api.ashx HTTP/1.1
Content-Type: application/x-www-form-url encoded
Host: http://api.url_endpoint.com
Content-Length: 467
Expect: 100-continue
Connection: Close

<Section>
    <LoginDetails>
        <Login>ABC</Login>
        <Password>ABCDE</Password>
    </LoginDetails>
</Section>

在文档中,它说:The XML should be in the body of the request.

问题1.如何将XML放入请求正文中?

问题2.注意HTTP/1.1,它是否应该作为API URL端点的后缀连接?

这就是我尝试过的方式。

$header_options = [
    'headers' => [
            'Accept' => 'application/xml',
            'Content-Type' => 'application/x-www-form-url encoded',
            'Host' => 'http://api.url_endpoint.com',
            'Content-Length' => 467,
            'Expect' => '100-continue',
            'Connection' => 'Close',
    ],
    'body' => '<Section><LoginDetails><Login>ABC</Login><Password>ABCDE</Password></LoginDetails></Section>',
];

$response = $client->request('POST', 'http://api.url_endpoint.com/my_api.ashx', $header_options);

dump($response->xml());

但我仍然得到400 Bad Request作为回复。

php xml laravel api guzzle
1个回答
0
投票

首先,尝试使用Content-Type标头值的修复:application/x-www-form-urlencoded(不是application/x-www-form urlencoded)。

如果这不起作用,也尝试解析这样的身体:

$header_options = [
    'headers' => [
            ...
            'Content-Type' => 'application/x-www-form-urlencoded'
            ...
    ],
    ...
    'body' => urlencode('<Section><LoginDetails><Login>ABC</Login><Password>ABCDE</Password></LoginDetails></Section>'),
];

如果这不起作用,您可以尝试以这种方式更改标头集:

$header_options = [
    'headers' => [
            ...
            'Content-Type' => 'text/xml', // also try 'application/xml'
            ...
    ],
    ...
];

如果其中一个想法对你有帮助,请告诉我:)

© www.soinside.com 2019 - 2024. All rights reserved.