有時(shí)使用HttpWebRequest對(duì)象會(huì)出現(xiàn)錯(cuò)誤,總結(jié)有三種:
1、System.Net.WebException: 服務(wù)器提交了協(xié)議沖突. Section=ResponseStatusLine
2、System.Net.WebException: 基礎(chǔ)連接已經(jīng)關(guān)閉: 連接被意外關(guān)閉。
3、System.Net.ProtocolViolationException: 無法發(fā)送具有此謂詞類型的內(nèi)容正文。
使用TcpClient對(duì)象搞定:
復(fù)制代碼 代碼如下:
private string GetHTMLTCP(string URL)
{
string strHTML = "";//用來保存獲得的HTML代碼
TcpClient clientSocket = new TcpClient();
Uri URI = new Uri(URL);
clientSocket.Connect(URI.Host, URI.Port);
StringBuilder RequestHeaders = new StringBuilder();//用來保存HTML協(xié)議頭部信息
RequestHeaders.AppendFormat("{0} {1} HTTP/1.1\r\n", "GET", URI.PathAndQuery);
RequestHeaders.AppendFormat("Connection:close\r\n");
RequestHeaders.AppendFormat("Host:{0}\r\n", URI.Host);
RequestHeaders.AppendFormat("Accept:*/*\r\n");
RequestHeaders.AppendFormat("Accept-Language:zh-cn\r\n");
RequestHeaders.AppendFormat("User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\r\n\r\n");
Encoding encoding = Encoding.Default;
byte[] request = encoding.GetBytes(RequestHeaders.ToString());
clientSocket.Client.Send(request);
//獲取要保存的網(wǎng)絡(luò)流
Stream readStream = clientSocket.GetStream();
StreamReader sr = new StreamReader(readStream, Encoding.Default);
strHTML = sr.ReadToEnd();
readStream.Close();
clientSocket.Close();
return strHTML;
}
使用 HttpWebRequest請(qǐng)求頁面
復(fù)制代碼 代碼如下:
///
/// 獲取html源碼
///
///
///
///
static string GetHTML(string url, string param)
{
try
{
Uri uri = new Uri(url);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
myReq.Headers.Add("Accept-Encoding", "gzip,deflate");//sdch
byte[] byData = Encoding.Default.GetBytes(param);
myReq.Method = "post";
myReq.ContentLength = byData.Length;
Stream reqStrem = myReq.GetRequestStream();
reqStrem.Write(byData, 0, byData.Length);
reqStrem.Close();
HttpWebResponse result = (HttpWebResponse)myReq.GetResponse();
Stream recStream = result.GetResponseStream();
//如果是Gzip方式則需要解壓
recStream = new GZipStream(recStream, CompressionMode.Decompress);
StreamReader redStream = new StreamReader(recStream, System.Text.Encoding.Default);
string strHTML = redStream.ReadToEnd();
redStream.Close();
recStream.Close();
result.Close();
return strHTML;
}
catch (Exception)
{
return "";
}
}
您可能感興趣的文章:- C#中HttpWebRequest的用法詳解
- HttpWebRequest和HttpWebResponse用法小結(jié)
- C#采用HttpWebRequest實(shí)現(xiàn)保持會(huì)話上傳文件到HTTP的方法
- HttpWebRequest出錯(cuò).Section=ResponseHeader Detail=CR
- .net core并發(fā)請(qǐng)求發(fā)送HttpWebRequest的坑解決