乐闻世界logo
搜索文章和话题

How do I POST XML data with curl

1个答案

1

When using the curl command to send a POST request with XML data, the process generally involves the following steps:

1. Prepare XML Data

First, prepare the XML-formatted data. Assume the following XML data is to be sent:

xml
<?xml version="1.0" encoding="UTF-8"?> <Request> <Name>Zhang San</Name> <Email>zhangsan@example.com</Email> </Request>

2. Send POST Request Using curl

Next, use the curl command to send a POST request. Key points include setting the correct HTTP headers and request body:

  • -X POST specifies the request type as POST.
  • -H "Content-Type: application/xml" sets the content type to XML.
  • -d @filename.xml reads data from the file filename.xml. If the data is provided directly in the command line, you can use -d '...'.

Example Commands:

If the XML data is saved in the request.xml file, the command is:

bash
curl -X POST -H "Content-Type: application/xml" -d @request.xml http://example.com/api

If the data is provided directly in the command line, the command is:

bash
curl -X POST -H "Content-Type: application/xml" -d '<?xml version="1.0" encoding="UTF-8"?><Request><Name>Zhang San</Name><Email>zhangsan@example.com</Email></Request>' http://example.com/api

3. Handle Server Responses

After sending the request, curl outputs the server's response. Review these responses to confirm if the data was successfully sent and processed. You can also use the -o parameter to save the response to a file or the -i parameter to view the response headers.

Example:

bash
curl -i -X POST -H "Content-Type: application/xml" -d @request.xml http://example.com/api

This command displays the HTTP response headers and content, helping you further debug and validate the request.

Summary

The key to sending XML data with curl is correctly setting the HTTP headers and data format. With simple command-line operations, you can flexibly send HTTP requests, which is highly suitable for testing and automation tasks.

2024年8月13日 22:38 回复

你的答案