尝试使用curl soap发送请求时,php Length必需的错误

时间:2014-08-04 06:02:54

标签: php curl soap libcurl

我需要以这种格式形成一个请求:

    POST /CJW/cjws.asmx HTTP/1.1
Host: www.somesite.abc.edu.sg
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/GetAll"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetAll xmlns="http://tempuri.org/">
      <ErrorMsg>string</ErrorMsg>
    </GetAll>
  </soap:Body>
</soap:Envelope>

所以这就是我的尝试:

<?php
$username = '';
$password = '';
$credentials = $username.":".$password; 
//$url = "http://tempuri.org/GetAll";
$url = "http://www.somesite.abc.edu.sg/GetAll";

$soap_request = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetAll xmlns="http://tempuri.org/">
      <ErrorMsg>string</ErrorMsg>
    </GetAll>
  </soap:Body>
</soap:Envelope>';

$header = array(
"POST /CJW/cjws.asmx HTTP/1.1 \n",
"Host: www.somesite.abc.edu.sg \n",
"Content-type: text/xml; charset=\"utf-8\" \n",
"Content-length: ".strlen($soap_request)." \n",
"SOAPAction: ".$url." \n");


$curl = curl_init(); 


curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888'); 
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ; 
curl_setopt($curl, CURLOPT_USERPWD, $credentials); 
curl_setopt($curl, CURLOPT_SSLVERSION,3); 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); 
curl_setopt($curl, CURLOPT_HEADER, true); 
curl_setopt($curl, CURLOPT_POST, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $soap_request );
curl_setopt($curl, CURLOPT_HTTPHEADER,     $header);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 
curl_setopt($curl, CURLOPT_URL, $url);

// perform the request

$xml_result = curl_exec($curl);
// check for errors
if ($xml_result === false) {
$error_occurred = true;
}
else {

    echo $xml_result;
}
?>

但我无法正确得到答案,实际上,除了这个错误我没有看到答案:

Length Required
HTTP Error 411. The request must be chunked or have a content length.

我尝试了很多方法,包括删除长度部分,用一些修正号更改它等等,但它没有任何改变。 那我在这里做错了什么?怎么样正确的方法? 非常感谢!

1 个答案:

答案 0 :(得分:0)

(您可以从您合成的标题中删除Host:和Content-Length:因为如果您不设置它们,curl会自己添加它们。)

您应该详细检查您的传出请求,并验证它看起来完全符合您的要求。使用CURLOPT_VERBOSE通常就足够了,但你需要能够在某处获取输出以供检查。

我相信你的自定义标题都有一个尾随空格和一个你应该删除的换行符。他们将严重搞砸了传出的请求。哦,必须从自定义标题中删除 POST 部分(它不是标题,而是“请求行”)。