Stewart Alan
Stewart Alan

Reputation: 1643

Making Synchronous xmlhttp request in code behind

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

Upvotes: 1

Views: 193

Answers (2)

I4V
I4V

Reputation: 35353

I don't think your problem is related to sync/async operations. Your code to convert the string to byte array

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

is similar to Unicode encoding(2 bytes per char).

See the differences among encodings

string UpliftJobXMLString = "abcÜ";

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

Therefore, either set the content-encoding to unicode or use another encoding. For ex;

objRequest.ContentType = "text/xml; charset=utf-8";

Upvotes: 1

Muhwu
Muhwu

Reputation: 1181

I'm fairly certain that this is not an async issue. Have you checked what sr.ReadToEnd() returns before the HtmlDecode?

Furthermore, you should check that the server is returning what you're expecting for it to return. Check the response StatusCode and StatusDescription. If your server is throwing an internal server exception (500) or something similar, the response string you read would come up empty as the content of the response would not be sent by the server in the first place.

Upvotes: 2

Related Questions