2011-06-15 162 views
0

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=C#中POST請求參數的問題

這裏是頭:

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請求(或其他whetever的伎倆)。這是我的嘗試:

 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(); 

但它不起作用。響應代碼是OK,但響應本身是這樣的:

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),所以我可以看到參數有問題。

回答

1

稍後指定UTF-8時,不要進行ASCII編碼。確保網址編碼參數。嘗試將內容類型更改爲「x-www-form-urlencoded」。

2

爲什麼不使用NameValueCollection來使用WebClient發佈參數?它爲你做了棘手的事情。鏈接頁面底部的代碼非常簡單。與樣本不同,您應該仔細處理WebClient的處理。