C# 多线程 HTTP request
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
//by wgscd
//2011-8-25
namespace TesMutiRequest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
delDisplay = new deldisp(display);
}
delegate void deldisp(string strInput);
deldisp delDisplay;
Util tool = new Util();
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread th = new Thread(new ThreadStart(doLoadpage));
th.Start();
}
}
int icount = 0;
void doLoadpage() {
Random rnd = new Random();
while (true)
{
icount++;
string strResult = tool.getPage("http://www.112.com/?t=" + rnd.Next(12222, 45555).ToString(),"get",null );
if (strResult.StartsWith("err"))
{
display(icount.ToString()+" : "+strResult);
}
else
{
display(icount.ToString() + " : ok");
}
Thread.Sleep(122);
}
}
void display(string strInput)
{
if (InvokeRequired)
{
Invoke(delDisplay, strInput);
}
else
{
txtReport.AppendText("[" + DateTime.Now.ToString() + "]" + strInput + "\r\n");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.ExitThread();
}
}
}
-----------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
namespace TesMutiRequest
{
class Util
{
public Util() {
proxy.Credentials = new NetworkCredential("wgscd","32423432");
}
WebProxy proxy = new WebProxy("proxy.cd.ncsi.com.cn",8080);
public string getPage(string strUrl, string strMethod, byte[] strData)
{
try
{
WebClient wc = new WebClient();
//使用代理
wc.Proxy = proxy;
//wc.Headers.Add("Set-Cookie", Common.cookie);
wc.Headers.Add("Method", strMethod);
wc.Encoding = Encoding.GetEncoding("gb2312");
wc.Headers.Add("ContentType", "application/x-www-form-urlencoded");
// wc.Headers.Add("AcceptEncoding", "gzip,deflate,sdch");
if (strMethod.ToUpper() == "POST")
{
return Encoding.UTF8.GetString(wc.UploadData(strUrl, strData));
}
else {
return wc.DownloadString(strUrl);
}
}
catch (Exception ex)
{
return "err:" + ex.Message;
}
}
}
}