【问题标题】:How to use Guzzle to send API request to the Restful that supports only XML format?如何使用 Guzzle 向仅支持 XML 格式的 Restful 发送 API 请求?
【发布时间】:2025-11-26 15:35:01
【问题描述】:

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

现在有一个仅支持XML 格式的新Restful API。我不知道如何使用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】:

    首先,尝试仅修复 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'
                ...
        ],
        ...
    ];
    

    如果这些想法之一对您有帮助,请告诉我 :)

    【讨论】:

    • 从我上面的例子中,一切都是正确的,除了我不应该在headers 中包含Host 元素。