0

我有这个代码

// 网络请求部分

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 循环程序的第三步显示 Form1 并冻结。可能我应该在 web_request 部分关闭一些东西..有什么建议吗?

4

1 回答 1

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

尝试这个..

于 2012-09-08T20:37:50.847 回答