欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HttpWebRequest的常见错误使用TcpClient可避免

程序员文章站 2024-03-03 18:42:46
有时使用httpwebrequest对象会出现错误,总结有三种: 1、system.net.webexception: 服务器提交了协议冲突. section=respon...
有时使用httpwebrequest对象会出现错误,总结有三种:
1、system.net.webexception: 服务器提交了协议冲突. section=responsestatusline
2、system.net.webexception: 基础连接已经关闭: 连接被意外关闭。
3、system.net.protocolviolationexception: 无法发送具有此谓词类型的内容正文。
使用tcpclient对象搞定
复制代码 代码如下:

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\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);
//获取要保存的网络流
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 "";
}
}