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
Related
This question already has answers here:
Send HTTP POST request in .NET
(16 answers)
Closed 5 years ago.
I have a Node server hosted with Azure, where I can send a POST request to the API for it to perform some function. The API itself works, I have tested it with Post Man.
A call to the API would look something like this..
http://website.com/api/Foo?name=bar&second=example
This doesn't necessarily need to return anything, as the call is silent and does something in the background. (note: perhaps it must return something and this is a hole in my understanding of the concept?)
Using C#, how can I make a web request to this URL?
I am already constructing the URL based on parameters passed to my method (so name and type as above could be whatever was passed to the method)
It's the POSTing to this URL that I cannot get working correctly.
This is the code I have tried..
void MakeCall(string name, string second)
{
string url = "http://website.com/api/Foo?name="+name+"&second="+second;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = url.Length;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
You have to create a request stream and write to it, this link here has several ways to do this either with HttpWebRequest, HttpClient or using 3rd party libraries:
Posting data using 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.
It seems to be occurring only one machine and none of the other machines.
HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("https://connect.zystemsgo.com/auto/");
myRequest.Method = "GET";
SetCertificatePolicy();
Application.DoEvents();
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(),System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
I tried searching other 400 request errors, but it is not clear. How do I go about debugging this?
HTTP Error 400 means Bad Request. This is being returned by the server.
Usually, when I'm debugging HTTP requests, I use Fiddler to monitor the requests and responses and find out what's going on. It never fails.
(Not really an answer, but too big for comment)
For what it's worth, I ran the following Python code (too lazy to spin up C# :), and it worked fine:
import httplib
conn = httplib.HTTPSConnection('connect.zystemsgo.com')
conn.request('GET', '/auto/')
resp = conn.getresponse()
data = resp.read()
print data # expected ouput, just like visiting in a browser
print resp.status # 200
Are you sure you are showing us the URL that is actually failing, or is your code a more general example?
Perhaps the server certificate is not installed on that machine? I wouldn't expect a HTTP 400 in that case, but it's the only thing I can think of so far...
it is a bad request error .Are there no parameters in the request?
Can you post the response message,it will give some idea of what is going wrong.
The code that i supplied in the comment above works.
WebClient webClient = new WebClient();
webClient.DownloadFile("Your complete url for the file", #"c:\myfile.txt");
you need to have permission to write in the directory of your choice.
You could also try and use the async download if you want.I am not getting why it would not work on a certain machine.
I'm sending an HTTPWebRequest to a 3rd party with the code below. The response takes between 2 and 22 seconds to come back. The 3rd party claims that once they receive it, they are sending back a response immediately, and that none of their other partners are reporting any delays (but I'm not sure I believe them -- they've lied before).
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com");
request.Timeout = 38000;
request.Method = "POST";
request.ContentType = "text/xml";
StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(XMLToSend); // XMLToSend is just a string that is maybe 1kb in size
streamOut.Close();
HttpWebResponse resp = null;
resp = (HttpWebResponse)request.GetResponse(); // This line takes between 2 and 22 seconds to return.
StreamReader responseReader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
Response = responseReader.ReadToEnd(); // Response is merely a string to hold the response.
Is there any reason that the code above would just...pause? The code is running in a very solid hosting provider (Rackspace Intensive Segment), and the machine it is on isn't being used for anything else. I'm merely testing some code that we are about to put into production. So, it's not that the machine is taxed, and given that it is Rackspace and we are paying a boatload, I doubt it is their network either.
I'm just trying to make sure that my code is as fast as possible, and that I'm not doing anything stupid, because in a few weeks, this code will be ramped up to run 20,000 requests to this 3rd part every hour.
Try doing a flush before you close.
streamOut.Flush();
streamOut.Close();
Also download microsoft network monitor to see for certain if the hold up is you or them, you can download it here...
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=983b941d-06cb-4658-b7f6-3088333d062f&displaylang=en
There is a few things that I would do:
I would profile the code above and get some definitive timings.
Implement the using statements in order to dispose of resources correctly.
Write the code in an async style there's going to be an awful lot of IO wait once its ramped.
Can you hit the URL in a regular ole browser? How fast is that?
Can you hit other URL's (not your partner's) in this code? How fast is that?
It is entirely possible you're getting bitten by the 'latency bug' where even an instant response from your partner results in unpredictable delays from your perspective.
Another thought: I noticed the https in your URL. Is it any faster with http?
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.