C#中使用HttpWebRequest發送網絡請求,HttpWebResponse接收網絡請求
具體如下:
一、HttpWebRequest
1、HttpWebRequest 發送Get請求:
//請求的地址
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://api.qq.com/tok?type=cli");
//請求方法
req.Method = "GET";
//數據內容類型
req.ContentType = "application/json";
//請求的超時時間 10秒還沒出來就超時
req.Timeout = 10000;
//接收響應的結果
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
//接收HTTP響應的數據流
using (Stream resStream = response.GetResponseStream())
{
//把數據流存入StreamReadr,選用編碼格式
using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
{
//通過ReadToEnd()把整個HTTP響應作為一個字符串取回,
//也可以通過 StreamReader.ReadLine()方法逐行取回HTTP響應的內容。
string responseContent = reader.ReadToEnd().ToString();
}
}
HTTP 內容類型(Content-Type)
普通文本 "text/plain";
JSON字符串 "application/json";
未知類型(數據流) "application/octet-stream";
表單數據(鍵值對) "application/x-www-form-urlencoded";
表單數據(鍵值對)編碼方式為 gb2312 "application/x-www-form-urlencoded;charset=gb2312";
表單數據(鍵值對)編碼方式為 utf-8 "application/x-www-form-urlencoded;charset=utf-8";
多分部數據 "multipart/form-data";
提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。
該ContentType的屬性包含請求的媒體類型。分配給ContentType屬性的值在請求發送Content-typeHTTP標頭時替換任何現有內容。
要清除Content-typeHTTP標頭,請將ContentType屬性設置為null。
2、HttpWebRequest 發送Post請求:
public static string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";//"application/x-www-form-urlencoded";
request.ContentLength = postDataStr.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默認編碼
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
}