C# wnform 請求http ( get , post 兩種方式 )

來源:互聯網
上載者:User

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";
}

?>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.