2012-04-18 50 views
0

我試圖將數據發佈到網站並從服務器獲取響應。這是我使用的代碼:發佈數據並在asp.net中獲取響應

// Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create("http://www.indianrail.gov.in/train_Schedule.html"); 
    ((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:9.0) Gecko/20100101 Firefox/9.0"; 
    // Set the Method property of the request to POST. 
    request.Method = "POST"; 
    // Create POST data and convert it to a byte array. 
    string postData = lccp_trnname.Text; 
    byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
    // Set the ContentType property of the WebRequest. 
    request.ContentType = "application/x-www-form-urlencoded"; 
    // Set the ContentLength property of the WebRequest. 
    request.ContentLength = byteArray.Length; 
    // Get the request stream. 
    Stream dataStream = request.GetRequestStream(); 
    // Write the data to the request stream. 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    // Close the Stream object. 
    dataStream.Close(); 
    // Get the response. 
    try 
    { 
     WebResponse response = request.GetResponse(); 
     // Display the status. 
     Response.Write(((HttpWebResponse)response).StatusDescription); 
     // Get the stream containing content returned by the server. 
     dataStream = response.GetResponseStream(); 
     // Open the stream using a StreamReader for easy access. 
     StreamReader reader = new StreamReader(dataStream); 
     // Read the content. 
     string responseFromServer = reader.ReadToEnd(); 
     // Display the content. 
     Response.Write(responseFromServer); 
     // Clean up the streams. 
     reader.Close(); 
     dataStream.Close(); 
     response.Close(); 
    } 
    catch (WebException ee) 
    { 
     Label1.Text = ee.Message; 

    } 

而不是從服務器獲取答覆回來,我得到重定向到在我張貼的數據相同的網頁。如果有人知道我的代碼出了什麼問題,Plz會幫助我。我一直在努力,但所有的努力都是徒勞的。所以plz幫助

+1

不知道更多關於您張貼到的網頁,有沒有什麼人可以幫助你的機會。你能發佈關於該頁面的任何細節嗎?你確定它期待一個POST而不是一個GET?是否需要某些領域存在?是否有反機器人技術? – CodingGorilla 2012-04-18 19:52:47

+0

其實我試圖使用這個簡單的HTML代碼發佈數據,它的工作。這是代碼: 示例HTML形式 <形式名稱= 「trn_num」 方法= 「POST」 行動= 「http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi」 > 。所以頁面需要一個POST,它只需要一個輸入。我不認爲有涉及反機器人技術。 – user1340945 2012-04-19 05:33:17

回答

2

您必須發佈數據http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi代替http://www.indianrail.gov.in/train_Schedule.html

UPDATE:

的第二個問題是,你不發送數據「lccp_trnname」參數的名稱。這將使它的工作:

string postData = "lccp_trnname=" + lccp_trnname.Text; 
+0

我試圖將數據發佈到http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi,但在那種情況下,我得到的答案是「訪問衝突」,因爲它是一個CGI頁面。 cgi頁面實際上是從http://www.indianrail.gov.in/train_Schedule.html獲取數據,並對其數據庫運行查詢,然後顯示結果。 – user1340945 2012-04-19 05:29:59

+0

thanx ....它的工作..! – user1340945 2012-04-21 08:15:10