2012-12-27 77 views
1

我正在與下面的代碼Get請求:HttpWebRequest的在C#

  TheRequest = (HttpWebRequest)WebRequest.Create(aURL); 
      TheRequest.Method   = "GET"; 
      TheRequest.CookieContainer = TheCookies; 
    TheRequest.UserAgent   = GetUserAgent(); 
    TheRequest.KeepAlive   = false; 
    TheRequest.Timeout  = 20000; 
      TheRequest.ReadWriteTimeout = 20000; 
    TheRequest.AllowAutoRedirect = true; 
    TheRequest.Headers.Add("Accept-Language", "en-us"); 
      TheResponse = (HttpWebResponse)TheRequest.GetResponse(); 
      TheResponseString = new StreamReader(TheResponse.GetResponseStream(), Encoding.ASCII).ReadToEnd(); 

在此之後我把餅乾如下:

string theCookieHeader = TheResponse.Headers[HttpResponseHeader.SetCookie]; 

然後我處理字符串是正確的cookie格式並將其放入cookie容器中以在下次POST請求中提供。從響應字符串(TheResponseString)我創建適當的發佈數據和來自cookiecontainer的cookie。

我對POST請求的代碼如下:

    TheRequest = (HttpWebRequest)WebRequest.Create(aURL); 
        TheRequest.Method   = "POST"; 
        TheRequest.CookieContainer = TheCookies; 
      TheRequest.UserAgent  = GetUserAgent(); 
      TheRequest.KeepAlive  = false;   
        TheRequest.Timeout    = 20000; 
        TheRequest.ReadWriteTimeout = 20000; 
      TheRequest.AllowAutoRedirect = true; 
      TheRequest.ContentType  = "application/x-www-form-urlencoded"; 
      TheRequest.Headers.Add("Accept-Language", "en-us"); 
        byte[] bytes = Encoding.ASCII.GetBytes(aPostDataString); 
      TheRequest.ContentLength = bytes.Length; 
      Stream oStreamOut = TheRequest.GetRequestStream(); 
      oStreamOut.Write(bytes,0,bytes.Length); 
      oStreamOut.Close(); 

        TheResponse = (HttpWebResponse)TheRequest.GetResponse(); 

        TheResponseString = new StreamReader(TheResponse.GetResponseStream(),       Encoding.ASCII).ReadToEnd(); 

現在的問題是我有兩個網站,他們是合作伙伴的網站,他們完全有相同的東西(這似乎但是如果你懷疑任何東西,那麼請告訴我),但對於一個網站,它工作正常,而對於其他網站,它給出了網站錯誤頁面的響應字符串。

請幫我看看診斷問題。

+0

你需要爲第二個提供不同的cookie,它發生在我身上!即使是相同的網站,但不同的子域名,有時你需要提供不同的cookie –

+4

那麼,如果你得到一個錯誤,你應該看看網站上的日誌失敗...你應該能夠看到*爲什麼*你得到一個錯誤。 –

+0

@JonSkeet我想他試圖連接到無法訪問的網站,btw關於李請求:)我已經安裝了SkeetNotifier,它太可愛了! –

回答

0

我有類似的問題。嘗試從請求中保存cookie,當您得到答覆或更好的時候,將此代碼放在finally區塊中。爲TheRequest.Host運行一次,第二次爲第二個站點的主機運行。另外看看你是否需要http或https

foreach (Cookie c in TheRequest.CookieContainer.GetCookies(new Uri("http://" + TheRequest.Host))) 
{ 
    TheCookies.SetCookies(new Uri("http://" + TheRequest.Host), c.Name + "=" + c.Value); 
} 
+0

我不知道爲什麼,但TheRequest.CookieContainer.GetCookies(新的URI( 「HTTP://」 + TheRequest.Host))不返回任何cookie的 – user1871770

+0

@ user1871770是U確保它的HTTP和HTTPS不是?你是否試圖用提琴手來跟蹤請求? – VladL

+0

是的,我做了,因爲在我的問題中,我有兩個階段,你能告訴我在哪裏放置代碼或嘗試你告訴的事情。我有餅乾容器作爲類級別的對象。 – user1871770