日期:2014-05-20  浏览次数:20758 次

关于HttpWebRequest的post问题
代码如下:
HttpWebRequest   myHttpWebRequest   =   (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.ContentType   =   "application/x-www-form-urlencoded ";
myHttpWebRequest.ContentLength   =   indata.Length;
myHttpWebRequest.Method   =   "POST ";
Stream   myRequestStream   =   myHttpWebRequest.GetRequestStream();
StreamWriter   myStreamWriter   =   new   StreamWriter(myRequestStream,   Encoding.GetEncoding( "gb2312 "));
myStreamWriter.Write(indata);
myStreamWriter.Close();
myRequestStream.Close();
//===
HttpWebResponse   myHttpWebResponse   =   (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream   myResponseStream   =   myHttpWebResponse.GetResponseStream();
StreamReader   myStreamReader   =   new   StreamReader(myResponseStream,   Encoding.GetEncoding( "gb2312 "));
outdata   =   myStreamReader.ReadToEnd();
myStreamReader.Close();

===以下删掉可以完成post吗?或者可以删改那些?
因为这个post程序对速度有要求,要在最短的时间内连续给几个url发送post
所以程序越快越好,考虑读取response可能浪费时间,如何删改代码能比较快
谢谢指教!


myResponseStream.Close();

------解决方案--------------------
HttpWebRequest请求得到的Response有时文件不全等,所以我现在都不用这个类。
最快就是自己写HTTP头,发送请求,然后获得回复。
public string CharSet = "GB2312 ";
public string Content = " ";
//页面的纯文字形式,标题(Title)和内容(Text)
public string Text;
public string Title;
//这个文件的路径
public string Uri;
public HtmlInfo(Uri uri)
{
this.Uri = uri.ToString();
byte[] buffer;
Encoding encoder = Encoding.GetEncoding(CharSet);
//建立HTTP头
string header = string.Format( "GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n ",
uri.PathAndQuery,
uri.Host);
//写入缓冲区
buffer = ASCIIEncoding.ASCII.GetBytes(header);
//建立TCP连接
TcpClient client = new TcpClient();
client.Connect(uri.Host, uri.Port);
NetworkStream ns = client.GetStream();
//发送HTTP头
ns.Write(buffer, 0, header.Length);

//建立接受缓冲区(512KB)
buffer = new byte[0x80000];
//计数变量
int count;
//本次接受到的字节数
count = ns.Read(buffer, 0, buffer.Length);
Content = Encoding.GetEncoding(CharSet).GetString(buffer,0,count);
Content = Content.Remove(0, Content.IndexOf( "\r\n\r\n ")+4);
client.Close();