0

我正在尝试将数据发布到网站并从服务器获取响应。这是我正在使用的代码:

    // 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;

    }

我没有从服务器获得回复,而是被重定向到我发布数据的同一网页。如果有人知道我的代码出了什么问题,请帮助我。很久以前我就一直在尝试,但所有的努力都白费了。所以请帮忙

4

1 回答 1

2

您必须将数据发布到http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi而不是http://www.indianrail.gov.in/train_Schedule.html

更新:

第二个问题是您没有在数据中发送“lccp_trnname”参数的名称。这将使它工作:

string postData = "lccp_trnname=" + lccp_trnname.Text;
于 2012-04-18T19:54:20.657 回答