PHP - HTTP Post - 不正确的标题

时间:2009-06-08 11:48:35

标签: php httpwebrequest http-headers

您好我正在尝试将xml文件发布到外部服务器,但我收到回复标题不正确的回复。我发布的服务器需要一些标题,我想知道它们是否格式正确,或者是否还需要包含其他“标准”标题?

我的代码是:

<?php

function httpsPost($Url, $xml_data, $headers)
{
   // Initialisation
   $ch=curl_init();
   // Set parameters
   curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); 
   curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
   curl_setopt($ch, CURLOPT_URL, $Url);
   // Return a variable instead of posting it directly
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch,CURLOPT_USERPWD,"username:password");
   // Active the POST method
   curl_setopt($ch, CURLOPT_POST, 1) ;
   // Request
   curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
   // execute the connexion
   $result = curl_exec($ch);
   // Close it
   curl_close($ch);
   return $result;
}

$headers[0]="BATCH_TYPE: XML_SINGLE"; 
$headers[1]="BATCH_COUNT: 1"; 
$headers[2]="VENDOR_ID: 53906";

$request_file = "./post_this.xml"; 
$fh = fopen($request_file, 'r'); 
$xml_data = fread($fh, filesize($request_file)); 
fclose($fh);    

$url = 'http://www.example.com/test.php';

$Response = httpsPost($url, $xml_data, $headers);

echo $Response;

?>

3 个答案:

答案 0 :(得分:0)

尝试

curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); 
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Accept: text/xml")); 

或使用

$header[] = "Host: ".$host; 
$header[] = "MIME-Version: 1.0"; 
$header[] = "Accept: text/xml";
$header[] = "Content-length: ".strlen($xmlRequest);
$header[] = "Cache-Control: no-cache";
$header[] = "Connection: close \r\n";
$header[] = $xmlRequest; // Contains the XML request 

链接可能有助于举例: http://www.nabble.com/Problems-posting-xml-file-with-curl-and-php-td16129807.html

答案 1 :(得分:0)

我对这个研究做了很多研究,但我没有任何明确的答案。我会说,我认为问题是你的标题是使用下划线而不是破折号。我想不出任何使用下划线的标准HTTP头。

根据HTTP 1.1 specification,这是完全合法的。根据RFC 2616:

message-header = field-name ":" [ field-value ]
field-name     = token
token          = 1*<any CHAR except CTLs or separators>
separators     = "(" | ")" | "<" | ">" | "@"
                  | "," | ";" | ":" | "\" | <">
                  | "/" | "[" | "]" | "?" | "="
                  | "{" | "}" | SP | HT

如果是一个选项,我建议将服务器更改为Batch-Type,Batch-Count和Vendor-Id。

如果Curl正在更改您背后的标题名称,则应report it as a bug

答案 2 :(得分:0)

如果我使用本地脚本作为发布的脚本,则输出正确。

本地脚本只包含

<?php
  phpinfo();
?>

所以,我想问题不在于您的代码,而在http://www.xhaus.com/headers显示。该网站似乎用破折号替换下划线进行显示。为什么要使用该URL来显示结果而不是您自己的phpinfo脚本?