doulao2916 2014-04-18 07:58
浏览 201
已采纳

如何使用XML格式的数据发出POST请求并获得结果

I have an API which says all requests are made as POST requests with data in XML format, and it gives me a sample XML data:

<?xml version="1.0" ?>
<Request>
    <SystemName>SomeSystemName</SystemName>
    <Client>SomeClientID</Client>
    <Method action="SomeAction">MethodParams</Method>
</Request>

Now I use curl to do it, like in this function:

function curl_post_xml($url, $xml, array $options = array()) 
{ 
    $defaults = array( 
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $xml,
        CURLOPT_HEADER => 0, 
        CURLOPT_URL => $url, 
        CURLOPT_FRESH_CONNECT => 1, 
        CURLOPT_RETURNTRANSFER => 1, 
        CURLOPT_FORBID_REUSE => 1, 
        CURLOPT_TIMEOUT => 4,
    ); 

    $ch = curl_init(); 
    curl_setopt_array($ch, ($options + $defaults)); 
    if( ! $result = curl_exec($ch)) 
    { 
        trigger_error(curl_error($ch)); 
    } 
    curl_close($ch); 
    return $result; 
} 

And in $xml I put that XML string from above. Am I doing it right? Because I heard that when using POST, the data must be in key-value format, but the API doesn't say anything about which variable should I assign XML string to.

  • 写回答

2条回答 默认 最新

  • duanliao6077 2014-04-18 15:59
    关注

    Am I doing it right? Because I heard that when using POST, the data must be in key-value format,

    Yes, you are right, you have to specify that you are sending an XML that's all.

    CURLOPT_HTTPHEADER => array("Content-Type: application/xml"),
    // or text/xml instead of application/xml
    

    You do not need to put the $xml under a key. Just pass it as you are doing, its fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误