C#代码如下所示:
private static string SendSoapRequest(string request, string destinationUrl)
{
string soapRequest = String.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<soap:Body>{0}</soap:Body></soap:Envelope>", request);
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(destinationUrl);
byte[] buffer = Encoding.UTF8.GetBytes(soapRequest);
req.Method = "POST";
req.ContentType = "application/soap+xml";
req.ContentLength = buffer.Length;
req.CookieContainer = new CookieContainer(); // enable cookies
req.Referer = "localhost";
req.Credentials = CredentialCache.DefaultCredentials;
Stream reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
reqst.Flush();
reqst.Close();
HttpWebResponse res = (HttpWebResponse) req.GetResponse();
Stream responseStream = res.GetResponseStream();
if (responseStream != null)
{
StreamReader sr = new StreamReader(responseStream);
string response = sr.ReadToEnd();
return response;
}
return string.Empty;
}
到目前为止,我的努力,以及许多其他变体,在PHP中没有成功:
public static function sendSoapCurl($samlMessage, $destination, $action) {
$headers = array(
"Content-type: application/soap+xml;charset=\"utf-8\"",
"Content-length: ".strlen($samlMessage),
);
if (isset($action)) {
$headers[] = "SOAPAction: $action";
}
// $samlMessage = utf8_encode($samlMessage);
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $destination);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $samlMessage); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// get soap response
$soapresponsexml = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
print_r("Status code: ".$httpCode."\n");
print_r($soapresponsexml);exit();
}
if ($soapresponsexml === null || $soapresponsexml === "") {
throw new \Exception('Empty SOAP response, check peer certificate.');
}
try {
$dom = new DOMDocument();
$dom = OneLogin_Saml2_Utils::loadXML($dom, $soapresponsexml);
} catch (RuntimeException $e) {
throw new \Exception('Not a SOAP response.', 0, $e);
}
$soapfault = self::getSOAPFault($dom);
if (isset($soapfault)) {
throw new \Exception($soapfault);
}
}
C#代码有效,但我无法在PHP中使用它。任何想法将不胜感激。感谢。
答案 0 :(得分:0)
在翻译中我错过了utf8编码部分。下面一行的添加解决了我的问题,现在请求有效:
$soapUtf8Request = utf8_encode($samlMessage);