1.Get請求
string strURL = "http://localhost/WinformSubmit.php?tel=11111&name=張三";
System.Net.HttpWebRequest request;
// 建立一個HTTP請求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
//request.Method="get";
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
MessageBox.Show(responseText);
2.Post請求
string strURL = "http://localhost/WinformSubmit.php";
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
//Post請求方式
request.Method = "POST";
// 內容類型
request.ContentType = "application/x-www-form-urlencoded";
// 參數經過URL編碼
string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("多月");
byte[] payload;
//將URL編碼後的字串轉化為位元組
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//佈建要求的 ContentLength
request.ContentLength = payload.Length;
//獲得請 求流
System.IO.Stream writer = request.GetRequestStream();
//將請求參數寫入流
writer.Write(payload, 0, payload.Length);
// 關閉請求流
writer.Close();
System.Net.HttpWebResponse response;
// 獲得響應流
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
MessageBox.Show(responseText);
註:System.Web.HttpUtility.UrlEncode("多月"); 需要引用 System.web.dll
WinformSubmit.php 代碼如下:
<?php
header("content-Type: text/html; charset=Utf-8");
echo mb_convert_encoding("123abc娃哈哈", "UTF-8", "GBK");
echo "\n------\n";
foreach($_POST as $key => $value){
echo $key . '--' .$value ."\n";
}
echo "\n-------\n";
foreach($_GET as $key => $value){
echo $key . '--' .$value ."\n";
}
?>