用调用一个SOAP接口,SOAPUI可以获取到,但在c#里实现出错
C#代码如下
string reqstr = "";
//reqstr += " < soapenv:Envelope xmlns:soapenv =\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tip=\"http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay\">";
// reqstr += " " ;
// reqstr += " " ;
// reqstr += " " ;
// reqstr += " " ;
reqstr += " " ;
reqstr += " " ;
reqstr += " tiptop\" password=\"tiptop\"/> ";
reqstr += " MES\" source=\"192.168.1.1\"/> ";
reqstr += " TESTSM\"/> ";
reqstr += " zh_tw\"/> ";
reqstr += " ";
reqstr += " " ;
reqstr += " " ;
reqstr += " " ;
reqstr += " sfb01\" value=\"\"/> ";
reqstr += " sfb05\" value=\"\"/> ";
reqstr += " sfb81\" value=\"\"/> ";
reqstr += " sfb04\" value=\"\"/> ";
reqstr += " ";
reqstr += " ";
reqstr += " ";
reqstr += "";
//reqstr += " ";
//reqstr += " ";
//reqstr += " ";
//reqstr += "";
string _url = "http://192.168.10.26/web/ws/r/aws_ttsrv2_toptest/";
Uri uri = new Uri(_url);
var request = (HttpWebRequest)WebRequest.Create(_url);
//WebRequest request = WebRequest.Create(uri);
request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "text/xml;charset=UTF-8";// "application/xml";
//request.ContentType = "application/x-www-form-urlencoded";
//request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.ProtocolVersion = HttpVersion.Version10;
//request.Timeout = 14000;
byte[] byteData = Encoding.UTF8.GetBytes(reqstr);
int length = byteData.Length;
request.ContentLength = length;
//request.ContentType = "gzip";
System.IO.Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, length);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
string rp = response.ToString();
远程服务器返回错误: (415) Unsupported Media Type。
该代码片段缺少了处理响应数据的代码。你需要使用 StreamReader 从 response 对象读取数据,例如:
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
Console.WriteLine(result);
}
服务器拒绝了你的请求,因为你提交的数据格式不支持。
你可以尝试在请求的头部添加下面的代码,以确保请求的数据格式正确:
request.Headers.Add("SOAPAction", "\"http://tempuri.org/GetWOData2Request\"");
返回错误代码 415 表示不支持的媒体类型。这可能是因为服务器无法识别您请求的内容类型,因此不能处理请求。
请确保在请求中设置的内容类型与接口期望的一致。在您的代码中,您设置了 ContentType = "text/xml;charset=UTF-8",请确保此内容类型是接口支持的,如果不支持,请使用接口所支持的正确的内容类型。
这个错误消息表明服务器无法识别你的请求的内容类型。 请确保请求的正文是以正确的格式编码的,并且内容类型头是正确的。
对于这个问题,你可以试试以下步骤:
1.确保请求的正文是以XML格式编码的,可以使用下面的代码:
byte[] byteData = Encoding.UTF8.GetBytes(reqstr);
int length = byteData.Length;
request.ContentLength = length;
request.ContentType = "text/xml; charset=utf-8";
System.IO.Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, length);
writer.Close();
2.如果还是不行,可以试试把请求的内容类型改为"application/soap+xml; charset=utf-8"。
如果仍然不能解决问题,可以尝试在请求头中添加Accept头,告诉服务器接受的内容类型,可以使用下面的代码:
request.Accept = "text/xml";
还有可以考虑检查服务器是否支持SOAP 1.2协议,并且确保你的请求遵循该协议的格式。