Easy alternative to HttpWebRequest for POST requests? - c#

I need to trigger an action on a remote server using an http POST request. The server sends a response, either Y or N, to inform me if the action suceeded or not.
I am looking at using HttpWebRequest to do this, but this seems too complex. To use this class you have to set all the headers, such as content type and content length.
Is there a quicker way to send a POST request that doesn't require setting lower level properties such as this?

Try this WebClient
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
byte[] responseArray = myWebClient.UploadData("YOUR URI","POST","DATA to be Posted");

You can try with WebClient class. It's much more simpler and it's basically a wrapper for HttpWebRequest. It encapsulate all this complex logic you're trying to avoid.

I think the easiest built in class in the framework is WebClient. Scott Hanselman has an example on how to perform gets and posts using it. This SO answer also has a good overview on how to post data.
If you have control over the server you're posting to, you might want to consider making it respond with HTTP status codes instead of some custom method.

the wcf web api project has an http client. It's super easy to use. http://wcf.codeplex.com/

Related

Open Internet Explorer browser with POST parameters

I would like to open a webpage in Internet Explorer using the WebBrowserTask but I would also like to pass a POST parameter(s) as well.
Is this possible using the WebBrowserTask?
EDIT: I forgot to mention that this is part of an XNA project. All I would like to do is to display a webpage and passing POST parameters with the request
You can also use the WebClient object to accomplish this though it is much more obscure. Webclient is a wrapper around HTTPRequest. It is like HTTPRequest on easy mode. The trade off is that if you want to send post data then you need to be crafty about it. You can create new headers in WebClient and set their names to what you need. Then when you make the call it will send them out as post data. Sounds complicated but actually pretty easy and clean when implemented. WAY cleaner than HTTPRequest.
WebBrowserTask can only navigate to a specific page and invoke GET request. You can simulate POST requests using the HttpWebRequest, but I doubt that will help you with what you are trying to do.
This is not possible with the WebBrowserTask, however it is possible using the WebBrowser control.
Specifically check out the Navigate method of WebBrowser.
This takes a byte[] with your POST data.
public void Navigate(
Uri uri,
byte[] postData,
string additionalHeaders)

Get HttpRequest full request string

I'm working on a proxy that will relay connections to another server. I had implemented a IHttpHandler that takes requests for a specific address and sends them to my proxy.
My proxy basically starts a sockect connection to the proxied server and reads the original request:
var requestString = new StreamReader(httpRequest.InputStream).ReadToEnd();
My problem arises at this point: the input stream only contains the stream of the body of the HTTP request, not the complete request.
How can I retrieve the full HTTP Request without having to reconstruct it from the HttpRequest object?
I don't know of a definitive one-liner in ASP .NET, but you can get pretty close, as shown in this forum post. What is suggested there is to build the first line out of HttpRequest properties, then add ServerVariables["ALL_RAW"], then the request body in the InputStream as you're already doing.
The only way to get the 'full HTTP Request' object is to actually reconstruct it in some way. I'm not sure you need the whole object for this process though. Perhaps you could just grab a subset of the items in HttpRequest for processing? You could manually concatenate the various portions of the object you need into something new. Once you deviate from using HttpRequest though, it's all custom to me.

Integrate a C# client into a node.js + socket.io chat app

As part of learning node.js, I just created a very basic chat server with node.js and socket.io. The server basically adds everyone who visits the chat.html wep page into a real time chat and everything seems to be working!
Now, I'd like to have a C# desktop application take part in the chat (without using a web browser control :)).
What's the best way to go about this?
I created a socket server in nodejs, and connected to it using TcpClient.
using (var client = new TcpClient())
{
client.Connect(serverIp, port));
using (var w = new StreamWriter(client.GetStream()))
w.Write("Here comes the message");
}
Try using the HttpWebRequest class. It is pretty easy to use and doesn't have any dependencies on things like System.Web or any specific web browser. I use it simulating browser requests and analyzing responses in testing applications. It is flexible enough to allow you to set your own per request headers (in case you are working with a restful service, or some other service with expectations of specific headers). Additionally, it will follow redirects for you by default, but this behavior easy to turn off.
Creating a new request is simple:
HttpWebRequest my_request = (HttpWebRequest)WebRequest.Create("http://some.url/and/resource");
To submit the request:
HttpWebResponse my_response = my_request.GetResponse();
Now you can make sure you got the right status code, look at response headers, and you have access to the response body through a stream object. In order to do things like add post data (like HTML form data) to the request, you just write a UTF8 encoded string to the request object's stream.
This library should be pretty easy to include into any WinForms or WPF application. The docs on MSDN are pretty good.
One gotcha though, if the response isn't in the 200-402 range, HttpWebRequest throws an exception that you have to catch. Fortunately you can still access the response object, but it is kind of annoying that you have to handle it as an exception (especially since the exception is on the server side and not in your client code).

HTTP library that doesn't depend on HttpWebRequest

I need a C# HTTP library that doesn't depend on HttpWebRequest, as I can't access this from the environment I need to run my code (Unity's WebPlayer).
Ideally this would be light weight, but any suggestions are welcome!
I just need to be able to do simple HTTP GET and POST requests, but better REST support would be good.
Thanks!
Edit: As people have pointed out, HttpWebRequest isn't in System.Web, but the fact remains - I can't use it. I've updated my post above.
This post
http://forum.unity3d.com/threads/24445-NotSupportedException-System.Net.WebRequest.GetCreator shows the same error I'm getting.
Implementing your own simple HTTP client using Socket is not all that difficult.
Just use TcpClient().
For the protocol itself, drop down to a connection-per-request paradigm. A typical GET request would look as follows:
GET /url HTTP/1.1
Host: <hostname-of-server>
Connection: close
For the code itself (from memory)
TcpClient client = new TcpClient();
IPEndPoint target = ... // get an endpoint for the target using DNS class
client.Connect(target);
using(NetworkStream stream = client.GetStream())
{
// send the request.
string request = "GET /url HTTP/1.1\r\nConnection: close\r\n\r\n";
stream.Write(Encoding.ASCII.GetBytes(request));
// then drain the stream to get the server response
}
Note that you will need to wrap this code with a simple class that provides HTTPWebRequest like semantics.
Look at System.Net.HttpWebRequest.
It is in System.dll.
Documentation: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
HttpRequest is located in System.Web, which is probably what you were thinking of.
HttpWebRequest is in the System assembly, not in System.Web (perhaps you're confusing with HttpRequest which is used in ASP.NET). It is available in all .NET Framework versions (including Silverlight, WP7, and Client Profile)

Change the Uri of a instance of HttpWebRequest?

I have an instance of an HttpWebRequest that I'm intercepting in an event.
I would like to edit the url before the request is sent but I can't find a way of doing this.
The property RequestUri is read only.
I've thought of a few ways but can't seem to find a working solution:
-Using reflection to set the value ?
-Creating a new request and then cloning all properties. not sure how to do that.
If you think in terms of the HTTP protocol, each request is stateless / unique. The only way to link one request to another is programmatically through something like Cookies, but to the HTTP protocol itself the request is unique.
I think the HttpWebRequest object was designed with this in mind. Each HttpWebRequest represents one unique call to a URL and you build up the parameters for that call. If you want to do another request to a different URL you would create a new HttpWebRequest and pass it the state information you are using, ie: Cookie container, header information etc.
The long winded answer to this is the object is designed to have a read only url and the only way to handle it is to:
Use a little reflection hack, such as you have already done, if you absolutely need to use the given HttpWebRequest object you have.
Create a new HttpWebRequest (WebRequest.Create()) and copy your state information over to the new request.
You can use RewritePath to do this.
F.e.
HttpContext.Current.RewritePath("newurl.aspx");

Categories

Resources