1

I am attempting to send XML to a URL and read the response, but the response is coming back empty every time. I think this is because its being processed Asynchronously and so the receiving code hasn't had a chance to complete by the time I read the response. In Javascrpt I would use

xmlhttp.Open("POST", url, false);   

to send a request Synchronously. How can I achieve it in C#?

My code is currently

HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Credentials = CredentialCache.DefaultCredentials;
objRequest.Method = "POST";
objRequest.ContentType = "text/xml";
Stream dataStream = objRequest.GetRequestStream();
byte[] bytes = new byte[UpliftJobXMLString.Length * sizeof(char)];
System.Buffer.BlockCopy(UpliftJobXMLString.ToCharArray(), 0, bytes, 0, bytes.Length);
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)objRequest.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
string respString = System.Web.HttpUtility.HtmlDecode(sr.ReadToEnd()); //always empty

Thanks

4

2 回答 2

2

我相当确定这不是异步问题。您是否检查过 sr.ReadToEnd() 在 HtmlDecode 之前返回的内容?

此外,您应该检查服务器是否正在返回您期望它返回的内容。检查响应 StatusCode 和 StatusDescription。如果您的服务器抛出内部服务器异常 (500) 或类似的东西,您读取的响应字符串将为空,因为响应的内容不会由服务器首先发送。

于 2013-05-22T11:26:17.117 回答
1

我认为您的问题与同步/异步操作无关。您将字符串转换为字节数组的代码

byte[] bytes = new byte[UpliftJobXMLString.Length * sizeof(char)];
System.Buffer.BlockCopy(UpliftJobXMLString.ToCharArray(), 0, bytes, 0, bytes.Length);

类似于 Unicode 编码(每个字符 2 个字节)。

查看编码之间的差异

string UpliftJobXMLString = "abcÜ";

byte[] bytesASCII = Encoding.ASCII.GetBytes(UpliftJobXMLString);
byte[] bytesUTF8 = Encoding.UTF8.GetBytes(UpliftJobXMLString);
byte[] bytesUnicode = Encoding.Unicode.GetBytes(UpliftJobXMLString);

因此,要么将内容编码设置为 unicode,要么使用其他编码。例如;

objRequest.ContentType = "text/xml; charset=utf-8";
于 2013-05-22T11:59:28.630 回答