HttpWebRequest Web Service调用返回请求格式无效:text/xml;charset=UTF-8

本文关键字:xml text charset UTF-8 无效 Service Web 调用 返回 格式 请求 | 更新日期: 2023-09-27 18:25:19

试图使用HTTPWebRequest调用WebService并发布数据,结果导致请求格式无效,我在客户端和WebService中都添加了http谓词,有什么想法吗?

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/WS/test.asmx/GetData");
String xmlString =  "Montreal";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "text/xml;charset=UTF-8";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();  //fails here with error message Request format is invalid: text/xml;charset=UTF-8.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);

HttpWebRequest Web Service调用返回请求格式无效:text/xml;charset=UTF-8

我修改了方法,这对我很有效。

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/WS/test.asmx");
String xmlData = "Montréal";
String xmlString = "<soapenv:Envelope xmlns:soapenv='"http://schemas.xmlsoap.org/soap/envelope/'" xmlns:tem='"http://tempuri.org/'"><soapenv:Header/>  <soapenv:Body><tem:GetData><tem:data>" + xmlData + "</tem:data></tem:GetData></soapenv:Body></soapenv:Envelope>";
byte[] bytesToWrite = Encoding.UTF8.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "text/xml;charset=UTF-8;";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
try
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
    Console.WriteLine(responseFromServer);
}
catch (Exception ex)
{
    string msg = ex.Message;
}