我将一个功能的端口从一个工作的C#类转换为一个PHP类 我尝试做一个非常简单的任务,但表现不同,我找不到问题,也许你们可以提供帮助。
这是C#代码(不是我的,按原样工作,隐藏敏感数据):
Stream requestStream = null;
HttpWebRequest webRequest = null;
StringBuilder postBuilder = null;
HttpWebResponse webResponse = null;
string requestUrl = null;
string cookieString = null;
byte[] rawPostData = null;
requestUrl = "https://some_server/Login";
webRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
postBuilder = new StringBuilder();
postBuilder.Append("<?xml version=\"1.0\" ?>");
postBuilder.Append("<authorization>");
postBuilder.Append("<username><![CDATA[some_name]]></username>");
postBuilder.Append("<password><![CDATA[some_password]]></password>");
postBuilder.Append("<domain><![CDATA[some_domain]]></domain>");
postBuilder.Append("</authorization>");
rawPostData = Encoding.Default.GetBytes(postBuilder.ToString());
webRequest.ContentType = "text/xml";
webRequest.Accept = "*/*,text/xml";
webRequest.ContentLength = rawPostData.Length;
webRequest.Method = "POST";
webRequest.UserAgent = "dsaxess/special";
requestStream = webRequest.GetRequestStream();
requestStream.Write(rawPostData, 0, rawPostData.Length);
requestStream.Flush();
webResponse = (HttpWebResponse)webRequest.GetResponse();
Debug.WriteLine("Status: " + webResponse.StatusCode);
//Debug.Write(webRequest.Headers);
//Debug.Write(webResponse.Headers);
requestStream.Close();
requestStream = null;
postBuilder = null;
Debug.WriteLine("Done!");
这是我的PHP代码:
$ch = curl_init();
$url = "https://some_server/Login";
$host = parse_url($url, PHP_URL_HOST);
//$path = parse_url($url, PHP_URL_PATH);
$xml_data = "<?xml version='1.0' ?>".
"<authorization>".
"<username><![CDATA[some_name]]></username>".
"<password><![CDATA[some_password]]></password>".
"<domain><![CDATA[some_domain]]></domain>".
"</authorization>";
$headers = array(
"Content-type: text/xml",
"Accept: */*,text/xml",
"User-Agent: dsaxess/special",
"Host: ".$host,
"Content-length: ".strlen($xml_data),
"Expect: 100-continue",
"Connection: Keep-Alive"
);
//var_dump($headers);
//var_dump($xml_data);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
var_dump(curl_getinfo($ch,CURLINFO_HTTP_CODE));
//var_dump($data);
curl_close($ch);
}
C#代码给出状态OK和有效的身份验证令牌。 PHP代码给出状态401和错误:用户不存在。
我不知道为什么会有所不同。 我比较了两者的请求和响应标题,并且一切看起来都一样。
请帮忙。
答案 0 :(得分:2)
自己解决了。标头语法错误。正确的语法是:
$headers = array(
"Content-type" => "text/xml",
"Accept" => "*/*,text/xml",
"User-Agent" => "dsaxess/special",
"Host" => $host,
"Content-length" => strlen($xml_data),
"Expect" => "100-continue",
"Connection" => "Keep-Alive"
);