post data and get back response in asp.net - c#

i am trying to post a data to a website and get the response back from the server. This is the code that i am using:
// 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;
}
instead of getting the reply back from the server, i am getting redirected to the same webpage in which i am posting the data. Plz help me if anyone has got any idea as what has gone wrong with my code. i've been trying since long back but all efforts went in vain. So plz help

You must post data to http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi instead of http://www.indianrail.gov.in/train_Schedule.html
UPDATE:
The second problem is that you are not sending name of "lccp_trnname" parameter in data. This will make it work:
string postData = "lccp_trnname=" + lccp_trnname.Text;

Related

Proper Way to open this URL in a C# app

I have a URL that I want to open in my C# app. This URL is used to talk to a communications device, not an internet web site. I have gotten by (I think) all the cert stuff. But the text I get back in the program IS NOT the same thing that CORRECTLY displays when I use a web browser.
Here's the code.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
namespace VMLConnStatus
{
class Program
{
static void Main(string[] args)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Create a request for the URL: https://192.168.30.15/cgi-bin/connstatus?202
String url = "https://192.168.30.15/cgi-bin/";
String data = "connstatus?202";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = data;
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.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
}
}
public class MyPolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint,
X509Certificate certificate, WebRequest request,
int certificateProblem)
{
//Return True to force the certificate to be accepted.
return true;
}
}
}
The result, though not perfectly displayed in Chrome, should be:
NA NA NA NA 4c:cc:34:02:6d:26 00:23:A7:24:A3:B6
But the text I get in the console window is:
Ok
<HTML>
<HEAD><TITLE>Index of cgi-bin/</TITLE></HEAD>
<BODY BGCOLOR="#99cc99" TEXT="#000000" LINK="#2020ff" VLINK="#4040cc">
<H4>Index of cgi-bin/</H4>
<PRE>
. 15Jun2014 09:48
0
.. 15Jun2014 09:48
0
connstatus 15Jun2014 09:48
19580
firmwarecfg 15Jun2014 09:48
45736
webcm 15Jun2014 09:48
23836
</PRE>
<HR>
<ADDRESS><A HREF="http://www.acme.com/software/mini_httpd/">mini_httpd/1.19 19de
c2003</A></ADDRESS>
</BODY>
</HTML>
Not EVEN close to the same thing.
What am I doing wrong?
Chuck
UPDATE: Code changed. URL, GET, and request writing (presuming I understood the directions). New code is:
static void Main(string[] args)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Create a request for the URL: https://192.168.30.15/cgi-bin/connstatus?202
String url = "https://192.168.30.15/cgi-bin/connstatus?202";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "GET";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Get the request stream.
//Now it throws an exception here--------------------------------
//"Cannot send a content-body with this verb-type."
Stream dataStream = request.GetRequestStream();
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
}
You are using http method POST but the url you have in the comment looks more like GET so then you probably need WebRequest.Create(url + data).
The incorrect response is the index page for https://192.168.30.15/cgi-bin/ which if you put into Chrome will give you the same "wrong" response.
You might not need to write any data to the request stream and can change the Method and ContentType for the request.
The solution required two parts.
First, doing the proper things, thus a total code rework.
I had the dreaded "The server committed a protocol violation. Section=ResponseHeader Detail=Header name is invalid". I tried to make the programatic solution for this work, but it is a .NET 2.0 solution and I was not able to figure it out in .NET4+. So, I edited the .config file and went on.
Here's the final code:
//Initialization
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(#"https://192.168.30.15/cgi-bin/connstatus?202");
//method is GET.
WebReq.Method = "GET";
//Get the response handle
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//read the response
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
//display it
Console.WriteLine(_Answer.ReadToEnd());
//pause for the ENTER key
Console.ReadLine();
This was added to the .config file in the debug folder (and would be added in the Release folder also..... using VS2013)
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
Thank-you to everyone that replied. The inspiration helped me get to the solution.

HttpWebRequest needs to wait 5 seconds to work properly in PUT method

I am trying to use an API and I don't have any problems with GET and POST but PUT isn't working. I tried with a lot of different examples and finally by chance I discovered that waiting more that 5 seconds (with 5000ms it is not working and with 5100ms it does) it starts working properly. But why is that happening? And how can I avoid this? 5 seconds for each registry update is to much waiting and I really don't understand why POST works well without waiting and PUT needs 5 seconds to work.
Here I put the method that I am using with the Thread.Sleep(5100). As I said without this line when I make WebResponse response = request.GetResponse(); gives me an error.
public void call(string url, object jsonObj)
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(urlSplio);
// Create POST data and convert it to a byte array.
request.Method = "PUT";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["User"], "WebConfigurationManager.AppSettings["Key"]");
string json = JsonConvert.SerializeObject(jsonObj);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// 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();
Thread.Sleep(5100);
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
I think you might want to rewrite the response stream code
Take a look at this walkthrough on MS MS walkthrough
private byte[] GetURLContents(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
// Send the request to the Internet resource and wait for
// the response.
// Note: you can't use HttpWebRequest.GetResponse in a Windows Store app.
using (WebResponse response = webReq.GetResponse())
{
// Get the data stream that is associated with the specified URL.
using (Stream responseStream = response.GetResponseStream())
{
// Read the bytes in responseStream and copy them to content.
responseStream.CopyTo(content);
}
}
// Return the result as a byte array.
return content.ToArray();
}

Http Request not sent from android C#

Iam developing a cross platform android app in Xamarin. I want to send a request to register my device. Iam sending my DeviceId, DeviceName and EncodedAccountName i.e my email id.
But I dont get any response. I have tested the request on Postman and get a proper response.
Here is my code:
StringBuilder registerContent = new StringBuilder();
registerContent.Append("DeviceId=").Append(deviceId).Append("&");
registerContent.Append("Name=").Append(deviceName).Append("&");
registerContent.Append("EncodedAccountNameā€¸=").Append(username);
WebRequest request = WebRequest.Create(EndPoints.RegisterDeviceEndPoint);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = registerContent.ToString();
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.
WebResponse response = request.GetResponse();// Dont get any response here
// Display the status.
System.Console.WriteLine(((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.
System.Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return response.ToString();
Any ideas on what might me going wrong?
Thanks
This is how I notify my Web API and wait for a string response:
string myParameters = "?firstParam=" + someParam1 + "&secondParam=" + someParam2;
string url = someHTTPAddress + myParameters;
stringResponseFromWebAPI = (new WebClient()).DownloadString(url);

post more than one data in asp.net with C# and get back the response

I'm trying to post data at "http://www.indianrail.gov.in/cgi_bin/inet_srcdest_cgi_time.cgi" using asp.net with C#. The problem is that the code that i am using is not able to post more than one data. This code has worked properly when i had posted just one data at "http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi" however this is not working when i am trying to post more than one data. Also there is one hidden field attached with each input data, so what do i have to do with that hidden field.
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "lccp_src_stncode=" + src;
postData += ("&lccp_dstn_stncode=" + des);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.indianrail.gov.in/cgi_bin/inet_srcdest_cgi_time.cgi");
myRequest.Method = "POST";
myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
//Get the stream containing content returned by the server.
newStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(newStream,Encoding.UTF8);
// Read the content.
string responseFromServer = reader.ReadToEnd();
File.WriteAllText(#"C:\Users\Zohaib\Documents\Visual Studio 2010\WebSites\WebSite4\App_Data\data.txt", responseFromServer);
// Clean up the streams.
reader.Close();
newStream.Close();
response.Close();
In a POST you simply provide a stream of data. Is that stream is to contain "two" things, you simply serialize both to the stream. In your case, if you want to send more thane one query string parameter, simply add that on to the string before you call GetBytes

(OAuthException - #2500) An active access token must be used to query information about the current user

string accessToken = GetAccessToken();
string accessKey = accessToken.Split('=')[1];
var client = new FacebookClient(accessKey);
dynamic me = client.Get("me");
here is the method to get access token and it does return a valid access token
private static string GetAccessToken()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=201193246663533&client_secret=secretkeyhere");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
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.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
However, when I debug over
dynamic me = client.Get("me");
throws this exception:
(OAuthException - #2500) An active access token must be used to query information about the current user.
How can i fix this?
you are getting access token for the APPLICATION, not for a user. Therefore, "me" does not make sense. You should supply ID there - either your user ID, or your app ID, or any other ID your app has permissions for.
both calls worked for with your example:
dynamic me = client.Get("1000<<MY_USER_ID>>5735");
dynamic theApp = client.Get("201193246663533");

Categories

Resources