使用.NET WebClient模拟XmlHttpRequest

时间:2011-05-21 02:42:53

标签: c# .net winforms xmlhttprequest webclient

带有XmlHttpRequest的AFAIK我可以使用send方法下载和上传数据。但WebClient有很多方法。我不想要WebClient的所有功能。我只想创建一个模拟XmlHttpRequest的对象,除了它没有XSS限制。我也不关心将响应作为XML或甚至现在作为字符串。如果我能把它作为一个足够好的字节数组。

我认为我可以使用UploadData作为我的通用方法,但在尝试使用它下载数据时失败,即使它返回响应。那么如何编写一个行为与XmlHttpRequest的{​​{1}}方法类似的方法呢?

修改:我发现了一个不完整的类,它正是send模拟器here。太糟糕了,整个代码都丢失了。

2 个答案:

答案 0 :(得分:7)

您可以尝试使用此静态函数执行相同的操作

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:)

答案 1 :(得分:2)

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