httpwebrequest发送POST请求,获取返回的头部值,急!
用抓包软件(Fiddler2)可以得知发送的包是这样的(是一个登入页面,我输入了帐号密码)
Header里是这样的
POST /login HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: 要登入的某网址/login
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 要登入的某网址
Content-Length: 103
Connection: Keep-Alive
Pragma: no-cache
Cookie: PHPSESSID=9a73683e21399713d6cddb270ec16c08; cnzz_a30020080=1; sin30020080=; rtime30020080=0; ltime30020080=1331033172518; cnzz_eid30020080=87021669-1331032392-
Textview里显示
charset=utf-8&jumpurl=%2F&username=我的帐号&password=我的密码&rememberme=1&input2=%E7%99%BB+%E5%BD%95
我用httpwebrequest模拟这个数据包
HttpWebRequest requestCookies = (HttpWebRequest)WebRequest.Create(要登入的某网址);requestCookies.ContentType = "application/x-www-form-urlencoded";requestCookies.Referer = "要登入的某网址/login";requestCookies.Headers.Set("Pragma", "no-cache");requestCookies.Accept = "text/html, application/xhtml+xml, */*";requestCookies.Headers.Set("Accept-Language", "zh-CN");requestCookies.Headers.Set("Accept-Encoding", "gzip, deflate");string temp = "PHPSESSID=22a234c094a7f36ba11e6d6767fc614c; cnzz_a30020080=0; sin30020080=; rtime30020080=0; ltime30020080=1330943336040; cnzz_eid30020080=78128217-1330939152-";requestCookies.Headers.Set("cookie", temp);requestCookies.Method = "POST"; Encoding encoding23 = Encoding.GetEncoding("utf-8");byte[] bytesToPost = encoding23.GetBytes("charset=utf-8&jumpurl=%2F&username=帐号&password=密码&rememberme=1&input2=%E7%99%BB+%E5%BD%95");requestCookies.ContentLength = bytesToPost.Length;System.IO.Stream requestStream = requestCookies.GetRequestStream();requestStream.Write(bytesToPost, 0, bytesToPost.Length);requestStream.Close();HttpWebResponse hwr = (HttpWebResponse)requestCookies.GetResponse();WebHeaderCollection head = hwr.Headers;IEnumerator iem = head.GetEnumerator();ArrayList value = new ArrayList();for (int i = 0; iem.MoveNext(); i++){string key=head.GetKey(i);value.Add(head.GetValues(key));} string filePath2 = @"c:\infor2.txt";FileStream fs2 = new FileStream(filePath2, FileMode.Open, FileAccess.ReadWrite);StreamWriter sw2 = new StreamWriter(fs2);fs2.SetLength(0);for (int i = 0; i < value.Count; i++){ sw2.WriteLine(value[i].ToString());}sw2.Close();
将value.Add(head.GetValues(key));换成value.Add(head.Get(key));应该就可以了,前者是返回了一个数组,肯定就是你这个结果了,后者是一个字符串。
[解决办法]
urlencode
HOOPCHINA....我×。。。。
[解决办法]
UrlEncode(str, Encoding.UTF8);
public string UrlEncode(string str, Encoding e)
{
if (str == null)
{
return null;
}
return Encoding.ASCII.GetString(UrlEncodeToBytes(str, e));
}