我有这段代码
// 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部分的内容.. 有什么建议吗?
答案 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();
}
}
试试这个..