http://www.cnblogs.com/cang12138/p/5896187.html
1、當參數的數據較大時。WebClient同步。
//實例化
WebClient client = new WebClient();
//地址 string path = "http://127.0.0.1/a/b"; //數據較大的參數 string datastr = "id=" + System.Web.HttpUtility.UrlEncode(ids); //參數轉流 byte[] bytearray = Encoding.UTF8.GetBytes(datastr); //采取POST方式必須加的header,如果改為GET方式的話就去掉這句話即可 client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//長度 client.Headers.Add("ContentLength", bytearray.Length.ToString()); //上傳,post方式,並接收返回數據(這是同步,需要等待接收返回值) byte[] responseData = client.UploadData(path, "POST", bytearray); //釋放 client.Dispose(); //處理返回數據(一般用json) string srcString = Encoding.UTF8.GetString(responseData);
2、當參數的數據較大時。WebClient異步(接上面的代碼)。
//綁定事件,為了獲取返回值
client.UploadDataCompleted += new UploadDataCompletedEventHandler(UploadDataCallback2);
//這里是url地址
Uri uri = new Uri(url);
//異步post提交,不用等待。
client.UploadDataAsync(uri, "POST", bytearray);
//接收返回值的方法
public static void UploadDataCallback2(Object sender, UploadDataCompletedEventArgs e)
{
//接收返回值
byte[] data = (byte[])e.Result;
//轉碼
string reply = Encoding.UTF8.GetString(data);
//打印日志
LogResult("返回數據:" + reply + "\n");
}
3、當參數的數據正常時
//地址 string url = "http://127.0.0.1:8080/action?id=" + id + ""; //實例化 WebClient client = new WebClient(); //上傳並接收數據 Byte[] responseData = client.DownloadData(url); //接收返回的json的流數據,並轉碼 string srcString = Encoding.UTF8.GetString(responseData);
4、超時時間設置
//需要新寫個類繼承WebClient,並重寫
//然后實例化,就可以設置超時時間了。
例:WebClient webClient = new WebDownload();
/// <summary>
/// WebClient 超時設置
/// </summary>
public class WebDownload : WebClient
{
private int _timeout;
// 超時時間(毫秒)
public int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
public WebDownload()
{
//設置時間
this._timeout = 60000000;
}
public WebDownload(int timeout)
{
this._timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var result = base.GetWebRequest(address);
result.Timeout = this._timeout;
return result;
}
}
5、WebRequest方式
//地址 string url = "http://127.0.0.1/a/b?pro=" + pro; //傳的參數 string datastr1 = "id=" + System.Web.HttpUtility.UrlEncode(ids); //轉成字節 byte[] bytearray1 = Encoding.UTF8.GetBytes(datastr1); //創建WebRequest HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url); //POST方式 webrequest.Method = "POST"; // <form encType=””>中默認的encType,form表單數據被編碼為key/value格式發送到服務器(表單默認的提交數據的格式) webrequest.ContentType = "application/x-www-form-urlencoded"; //獲取字節數 webrequest.ContentLength = Encoding.UTF8.GetByteCount(datastr1); //獲取用於寫入請求數據的 System.IO.Stream 對象 Stream webstream = webrequest.GetRequestStream(); //向當前流中寫入字節序列,並將此流中的當前位置提升寫入的字節數。 webstream.Write(bytearray1, 0, bytearray1.Length); //獲取返回數據 HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse(); //轉碼 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //返回的結果 string ret = sr.ReadToEnd(); //關閉 sr.Close(); response.Close(); webstream.Close();

