POST or GET method? - c#

We have a service provider that allows us to connect to his payment page for payments, however the code he uses is php but we would like to do it in asp.net.
Problem is I don't really understand what the method should be, POST or GET, basically we need to redirect to the client with underlying parameters(not query strings) and then our current page that calls the request must be redirected to the client page with the parameters as well.
I do get the response witch is basically markup, but that's not what I want, I want it to redirect to the payment page, can someone please tell me what I do wrong.Thanks
Here is my code I use for the POST Method:
string query = string.Format("description={0}&amount={1}&merchantIdent={2}&email={3}&transaction={4}&merchantKey={5}",
description.ToString(), amount.ToString(), merchantIdent.ToString(), email.ToString(), id.ToString(), merchantKey.ToString());
// Create the request back
string url = "https://www.webcash.co.za/pay";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.AllowAutoRedirect = true;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
req.AllowAutoRedirect = true;
StreamWriter stOut = new StreamWriter(req.GetRequestStream(),System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();
// Do the request
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string response = stIn.ReadToEnd();
stIn.Close();

Not sure I totally understand your question, but as your title goes, here is the difference between POST and GET:
The GET method passes variables through the url. This can be practical or impractical (for instance if you plan to pass sensitive material to another page)
The POST method does not pass variables through the url, it passes the variables behind the scenes.
You'll need to decide which better fits your situation.

Normally GETs are idempotent (meaning they don't change data). Use a GET if you want to be able to issue a request and not change anything. Use a POST if you're performing some sort of update/processing/etc.

Related

C# Async Webrequest

I need to call a url like the following, programmatically, using C#:
http://mysite.com/AdjustSound.php
This php file expects a SoundLevel from me. So, an example call would be something like that:
http://mysite.com/AdjustSound.php?SoundLevel=30
I have 2 questions:
1:
WebRequest request =
WebRequest.Create("http://mysite.com/AdjustSound.php?SoundLevel=30");
// Which one?
// request.Method = "GET";
// request.Method = "POST";
Question 1: Do I need to make a GET or POST request?
2:
Since, I'm making this http-call very frequently (10-20 times in a sec); I have some speed issues. So, I don't want my program to wait till this http call finishes and retrieves the result. I want that Webrequest to run asynchronously.
The other issue is that I don't need to see the results of this http call. I just want to invoke the server side. And even, I don't care if this call finished successfully or not... (If it fails, most probably I will adjust the sound a few milliseconds later. So, I don't care.) I wrote the following code:
WebRequest request =
WebRequest.Create("http://mysite.com/AdjustSound.php?SoundLevel=30");
request.Method = "GET";
request.BeginGetResponse(null, null);
Question 2 : Doest it seem ok to run this code? Is that ok to call request.BeginGetResponse(null, null); ?
EDIT
After reading the comments; I modified my code like the following:
WebClient webClient = new WebClient();
Uri temp = new Uri("http://mysite.com/AdjustSound.php?SoundLevel=30");
webClient.UploadStringAsync(temp, "GET", "");
Is that ok/better now?
Q: Do I need to make a GET or POST request?
A: This example effectively is a "GET" request. Here, I'd use "GET". If you had a form, I'd instead recommend "POST"
Q: I'm making this http-call very frequently (10-20 times in a sec); I
have some speed issues.
If you happen to have the luxury of using .Net 4.x, I'd strongly recommended looking at their "asynchronous APIs":
http://msdn.microsoft.com/en-us/library/hh191443%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/hh300224%28v=vs.110%29.aspx

Retrieve DOM data from site

Is there any chance to retrieve DOM results when I click older posts from the site:
http://www.facebook.com/FamilyGuy
using C# or Java? I heard that it is possible to execute a script with onclick and get results. How I can execute this script:
onclick="(JSCC.get('j4eb9ad57ab8a19f468880561') && JSCC.get('j4eb9ad57ab8a19f468880561').getHandler())(); return false;"
I think older posts link sends an Ajax request and appends the response to the page. (I'm not sure. You should check the page source).
You can emulate this behavior in C#, Java, and JavaScript (you already have the code for javascript).
Edit:
It seems that Facebook uses some sort of internal APIs (JSCC) to load the content and it's undocumented.
I don't know about Facebook Developers' APIs (you may want to check that first) but if you want to emulate exactly what happens in your browser then you can use TamperData to intercept GET requests when you click on more posts link and find the request URL and it's parameters.
After you get this information you have to Login to your account in your application and get the authentication cookie.
C# sample code as you requested:
private CookieContainer GetCookieContainer(string loginURL, string userName, string password)
{
var webRequest = WebRequest.Create(loginURL) as HttpWebRequest;
var responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
// Now you may need to extract some values from the login form and build the POST data with your username and password.
// I don't know what exactly you need to POST but again a TamperData observation will help you to find out.
string postData =String.Format("UserName={0}&Password={1}", userName, password); // I emphasize that this is just an example.
// cookie container
var cookies = new CookieContainer();
// post the login form
webRequest = WebRequest.Create(loginURL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;
// write the form values into the request message
var requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
webRequest.GetResponse().Close();
return cookies;
}
Then you can perform GET requests with the cookie you have, on the URL you've got from analyzing that JSCC.get().getHandler() requests using TamperData, and eventually you'll get what you want as a response stream:
var webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.CookieContainer = GetCookieContainer(url, userName, password);
var responseStream = webRequest.GetResponse().GetResponseStream();
You can also use Selenium for browser automation. It also has C# and Java APIs (I have no experience using Selenium).
Facebook loads it's content dynamically with AJAX. You can use a tool like Firebug to examine what kind of request is made, and then replicate it.
Or you can use a browser render engine like webkit to process the JavaScript for you and expose the resulting HTML:
http://webscraping.com/blog/Scraping-JavaScript-webpages-with-webkit/

C# REST client sending data using POST

I'm trying to send a simple POST request to a REST web service and print the response (code is below, mostly taken from Yahoo! developer documentation and the MSDN code snippets provided with some of the documentation). I would expect the client to send:
Request Method: POST (i.e. I expect $_SERVER['REQUEST_METHOD'] == 'POST' in PHP)
Data: foo=bar (i.e. $_POST['foo'] == 'bar' in PHP)
However, it seems to be sending:
Request Method: FOO=BARPOST
Data: (blank)
I know the API works as I've tested it with clients written in Python and PHP, so I'm pretty sure it must be a problem with my C#. I'm not a .NET programmer by trade so would appreciate any comments/pointers on how to figure out what the problem is - I'm sure it's something trivial but I can't spot it myself.
uri, user and password variables are set earlier in the code - they work fine with GET requests.
request = (HttpWebRequest) WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
string postData = "foo=bar";
request.ContentLength = postData.Length;
StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
postStream.Write(postData);
postStream.Close();
response = (HttpWebResponse) request.GetResponse();
The REST API is written in PHP, and the $_POST array is empty on the server when using the C# client.
Eventually found the HttpWebRequest.PreAuthenticate property which seems to solve the problem if the code is edited like so:
request = (HttpWebRequest) WebRequest.Create(uri);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
From the documentation I presume this forces authentication before the actual POST request is sent. I'm not sure why the class doesn't do this automatically (libraries for other languages make this process transparent, unless you explicitly turn it off), but it has solved the problem for me and may save someone else another 2 days of searching and hair-pulling.
For what it's worth, PreAuthenticate doesn't need to be set for GET requests, only POST, although if you do set it for a GET request everything will still work, but take slightly longer.

Generate http post request from controller

Forgive me if this is a stupid question. I am not very experienced with Web programming.
I am implementing the payment component of my .net mvc application. The component interacts with an external payment service. The payment service accepts http post request in the following form
http://somepaymentservice.com/pay.do?MerchantID=xxx&Price=xxx&otherparameters
I know this is dead easy to do by adding a form in View. However, I do not want my views to deal with third party parameters. I would like my view to submit information to my controller, then controller generates the required url and then send out the request. Following is the pseudo code.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PayForOrder(OrderForm order)
{
var url = _paymentService.GetUrlFromOrder(order);
SendPostRequest(url);
return View("FinishedPayment");
}
Is it possible to do so? Does c# have built-in library to generate http request?
Thanks in advance.
You'll want to use the HttpWebRequest class. Be sure to set the Method property to post - here's an example.
There certainly is a built in library to generate http requests. Below are two helpful functions that I quickly converted from VB.NET to C#. The first method performs a post the second performs a get. I hope you find them useful.
You'll want to make sure to import the System.Net namespace.
public static HttpWebResponse SendPostRequest(string data, string url)
{
//Data parameter Example
//string data = "name=" + value
HttpWebRequest httpRequest = HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = data.Length;
var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(data);
streamWriter.Close();
return httpRequest.GetResponse();
}
public static HttpWebResponse SendGetRequest(string url)
{
HttpWebRequest httpRequest = HttpWebRequest.Create(url);
httpRequest.Method = "GET";
return httpRequest.GetResponse();
}
It realy makes a difference if ASP.NET makes a request or the the client makes a request.
If the documentation of the the provider says that you should use a form with the given action that has to be submited by the client browser then this might be necessary.
In lots of cases the user (the client) posts some values to the provider, enters some data at the providers site and then gets redirected to your site again. You can not do this applicationflow on the serverside.

HTTP Post in C# console app doesn't return the same thing as a browser request

I have a C# console app (.NET 2.0 framework) that does an HTTP post using the following code:
StringBuilder postData = new StringBuilder(100);
postData.Append("post.php?");
postData.Append("Key1=");
postData.Append(val1);
postData.Append("&Key2=");
postData.Append(val2);
byte[] dataArray = Encoding.UTF8.GetBytes(postData.ToString());
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://example.com/");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = dataArray.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(dataArray, 0, dataArray.Length);
requestStream.Flush();
requestStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)httpRequest.GetResponse();
if (httpRequest.HaveResponse == true) {
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
String responseString = responseReader.ReadToEnd();
}
The outputs from this are:
webResponse.ContentLength = -1
webResponse.ContentType = text/html
webResponse.ContentEncoding is blank
The responseString is HTML with a title and body.
However, if I post the same URL into a browser (http://example.com/post.php?Key1=some_value&Key2=some_other_value), I get a small XML snippet like:
<?xml version="1.0" ?>
<RESPONSE RESULT="SUCCESS"/>
with none of the same HTML as in the application. Why are the responses so different? I need to parse the returned result which I am not getting in the HTML. Do I have to change how I do the post in the application? I don't have control over the server side code that accepts the post.
If you are indeed supposed to use the POST HTTP method, you have a couple things wrong. First, this line:
postData.Append("post.php?");
is incorrect. You want to post to post.php, you don't want post the value "post.php?" to the page. Just remove this line entirely.
This piece:
... WebRequest.Create("http://example.com/");
needs post.php added to it, so...
... WebRequest.Create("http://example.com/post.php");
Again this is assuming you are actually supposed to be POSTing to the specified page instead of GETing. If you are supposed to be using GET, then the other answers already supplied apply.
You'll want to get an HTTP sniffer tool like Fiddler and compare the headers that are being sent from your app to the ones being sent by the browser. There will be something different that is causing the server to return a different response. When you tweak your app to send the same thing browser is sending you should get the same response. (It could be user-agent, cookies, anything, but something is surely different.)
I've seen this in the past.
When you run from a browser, the "User-Agent" in the header is "Mozilla ...".
When you run from a program, it's different and generally specific to the language used.
I think you need to use a GET request, instead of POST. If the url you're using has querystring values (like ?Key1=some_value&Key2=some_other_value) then it's expecting a GET. Instead of adding post values to your webrequest, just put this data in the querystring.
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://example.com/?val1=" + val1 + "&val2=" + val2);
httpRequest.Method = "GET";
httpRequest.ContentType = "application/x-www-form-urlencoded";
....
So, the result you're getting is different when you POST the data from your app because the server-side code has a different output when it can't read the data it's expecting in the querystring.
In your code you a specify the POST method which sends the data to the PHP file without putting the data in the web address. When you put the information in the address bar, that is not the POST method, that is the GET method. The name may be confusing, but GET just means that the data is being sent to the PHP file through the web address, instead of behind the scenes, not that it is supposed to get any information. When you put the address in the browser it is using a GET.
Create a simple html form and specify POST as the method and your url as the action. You will see that the information is sent without appearing in the address bar.
Then do the same thing but specify GET. You will see the information you sent in the address bar.
I believe the problem has something to do with the way your headers are set up for the WebRequest.
I have seen strange cases where attempting to simulate a browser by changing headers in the request makes a difference to the server.
The short answer is that your console application is not a web browser and the web server of example.com is expecting to interact with a browser.
You might also consider changing the ContentType to be "multipart/form-data".
What I find odd is that you are essentially posting nothing. The work is being done by the query string. Therefore, you probably should be using a GET instead of a POST.
Is the form expecting a cookie? That is another possible reason why it works in the browser and not from the console app.

Categories

Resources