This网站都会使用POST发送数据。我用Firebug来检查它。目标网址为this。特定示例的后期数据(空格分隔)为LeagueID=9 GameDate=4-29-2011 Season=2010-2011 Refresh=false LastUpdateTime=01-01-1900 type=Matchups RefreshStartTime=15-5-2011-1308094688683 Week= conferenceID=
。
以下是标题:
Host scores.covers.com
User-Agent Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Referer http://scores.covers.com/basketball-scores-matchups.aspx
Content-Length 169
Content-Type text/plain; charset=UTF-8
Cookie __loooooooooongCookieString
我想使用WebRequest
发出POST请求(或其他方法)。这是我的尝试:
string parameters = "LeagueID=\"9\"&GameDate=\"4-29-2011\"&Season=\"2010-2011\"&Refresh=\"false\"&LastUpdateTime=\"01-01-1900\"&type=\"Matchups\"&RefreshStartTime=\"15-5-2011-1308094688683\"&Week=&conferenceID=";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://scores.covers.com/ajax/SportsDirect.Controls.LiveScoresControls.Scoreboard,SportsDirect.Controls.LiveScoresControls.ashx?_method=UpdateScoreboard&_session=no");
req.Method = "POST";
req.ContentLength = bytes.Length;
req.ContentType = "text/plain; charset=UTF-8";
Console.WriteLine(req.ContentLength); // 175
Stream reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
WebResponse resp = req.GetResponse();
Console.WriteLine(((HttpWebResponse)resp).StatusDescription); // OK
Stream respStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(respStream);
Console.WriteLine(reader.ReadToEnd());
resp.Close();
但它不起作用。响应代码没问题,但响应本身是这样的:
new Object();r.error = new ajax_error('System.FormatException','Input string was
not in a correct format.\r\nCould not retreive parameters from HTTP request.',0
)new Object();r.error = new ajax_error('System.ArgumentException','Object of typ
e \'System.DBNull\' cannot be converted to type \'System.Int32\'.',0)
这笔交易是什么?由于请求的内容长度为175(而不是Firefox发出的请求中的169),我可以看到params出现了问题。
答案 0 :(得分:2)
为什么不使用NameValueCollection使用WebClient发布参数?它为你做了一些棘手的事情。链接页面底部的代码非常简单。与示例不同,您应该仔细考虑处理WebClient。
答案 1 :(得分:1)
稍后指定UTF-8时,不要进行ASCII编码。确保url编码参数。尝试将内容类型更改为“x-www-form-urlencoded”。