WebResponse和WebRequest

时间:2012-09-08 20:23:53

标签: c#

我有这段代码

// Web请求部分

private static WebRequest Web_request(string ip)
{
    WebRequest request = WebRequest.Create("http://website/");
    request.Method = "POST";
    string postData = "a=1&b=2";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    return request;        
}

//网络响应部分

private static string Web_response(WebRequest request)
{
    WebResponse response = request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
    reader.Close();
    dataStream.Close();
    response.Close();

    return responseFromServer;
}

和主程序

void Main()
{
    for (int ii = 0; ii < counter; ii++)
    {
        req[ii] = Web_request(ip_ext[ii]);
    }
    for (int ii = 0; ii < counter; ii++)
    {
        string domen = Web_response(req[ii]);
    }
}

但是在Web_request循环程序的第3步显示Form1并冻结。可能我应该关闭web_request部分的内容.. 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您需要将方法分离为请求和响应

HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = Constants.HTTPVerbGet;
req.KeepAlive = false;
req.Accept = Constants.HTTPRequestType;
using (var webResponse = (HttpWebResponse)req.GetResponse())
{
    using (var reader = new StreamReader(webResponse.GetResponseStream()))
    {
        string objJson = reader.ReadToEnd().ToString();
    }
}

试试这个..