HttpWebRequestのよくあるエラーはTcpClientを使うと避けられます。
2568 ワード
HttpWebRequestを使うと、エラーが発生する場合があります。まとめは3つあります。3、System.Net.Protocolation Exception:この述語タイプの内容本文は送信できません。TcpClidentオブジェクトを使用して解決しました。
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
RequestHeaders.AppendFormat("{0} {1} HTTP/1.1\r
", "GET", URI.PathAndQuery);
RequestHeaders.AppendFormat("Connection:close\r
");
RequestHeaders.AppendFormat("Host:{0}\r
", URI.Host);
RequestHeaders.AppendFormat("Accept:*/*\r
");
RequestHeaders.AppendFormat("Accept-Language:zh-cn\r
");
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
\r
");
Encoding encoding = Encoding.Default;
byte[] request = encoding.GetBytes(RequestHeaders.ToString());
clientSocket.Client.Send(request);
//
Stream readStream = clientSocket.GetStream();
StreamReader sr = new StreamReader(readStream, Encoding.Default);
strHTML = sr.ReadToEnd();
readStream.Close();
clientSocket.Close();
return strHTML;
}
は、HttpWebRequest要求ページ
///
/// 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 "";
}
}
を使用します。