簡體   English   中英

使用.NET WebClient模擬XmlHttpRequest

[英]Emulate XmlHttpRequest with a .NET WebClient

帶有XmlHttpRequest AFAIK我可以使用send方法下載和上傳數據。 WebClient有很多方法。 我不想要WebClient所有功能。 我只是想創建一個模擬XmlHttpRequest的對象,除了它沒有XSS限制。 我也不關心將響應作為XML或甚至現在作為字符串。 如果我可以把它作為一個足夠好的字節數組。

我認為我可以使用UploadData作為我的通用方法,但是當嘗試使用它下載數據時它會失敗,即使它返回響應。 那么如何編寫一個行為與XmlHttpRequestsend方法一樣的方法呢?

編輯:我在這里找到了一個不完整的類,它正是一個XmlHttpRequest模擬器。 太糟糕了,整個代碼都丟失了。

您可以嘗試使用此靜態函數來執行相同操作

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;
}

h :)

您需要使用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM