Emulate XmlHttpRequest with .NET WebClient

AFAIK with XmlHttpRequest I can only upload and download data using the send method. But WebClient has many methods. I do not need all the features of WebClient . I just want to create an object that emulates an XmlHttpRequest , except that it has no XSS restrictions. I also do not want to receive the answer as XML or even as a string right now. If I can get it as an array of bytes, which is good enough.

I thought I could use UploadData as my universal method, but it fails when trying to upload data with it, even if it returns a response. So, how can I write a method that behaves like the XmlHttpRequest send method?

Edit: I found an incomplete class, which is exactly the XmlHttpRequest emulator here . Too bad that all the code is lost.

+6
source share
2 answers

You will need an HttpWebRequest .

 HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://thewebsite.com/thepage.html"); using(Stream s = rq.GetRequestStream()) { // Write your data here } HttpWebResponse resp = (HttpWebResponse)rq.GetResponse(); using(Stream s = resp.GetResponseStream()) { // Read the result here } 
+2
source

You can try this static function to do the same

 public static string XmlHttpRequest(string urlString, string xmlContent) { string response = null; HttpWebRequest httpWebRequest = null;//Declare an HTTP-specific implementation of the WebRequest class. HttpWebResponse httpWebResponse = null;//Declare an HTTP-specific implementation of the WebResponse class //Creates an HttpWebRequest for the specified URL. httpWebRequest = (HttpWebRequest)WebRequest.Create(urlString); try { byte[] bytes; bytes = System.Text.Encoding.ASCII.GetBytes(xmlContent); //Set HttpWebRequest properties httpWebRequest.Method = "POST"; httpWebRequest.ContentLength = bytes.Length; httpWebRequest.ContentType = "text/xml; encoding='utf-8'"; using (Stream requestStream = httpWebRequest.GetRequestStream()) { //Writes a sequence of bytes to the current stream requestStream.Write(bytes, 0, bytes.Length); requestStream.Close();//Close stream } //Sends the HttpWebRequest, and waits for a response. httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); if (httpWebResponse.StatusCode == HttpStatusCode.OK) { //Get response stream into StreamReader using (Stream responseStream = httpWebResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) response = reader.ReadToEnd(); } } httpWebResponse.Close();//Close HttpWebResponse } catch (WebException we) { //TODO: Add custom exception handling throw new Exception(we.Message); } catch (Exception ex) { throw new Exception(ex.Message); } finally { httpWebResponse.Close(); //Release objects httpWebResponse = null; httpWebRequest = null; } return response; } 

hnd :)

+7
source

Source: https://habr.com/ru/post/888683/


All Articles