The Life and Times of a Dev

Yes, we're really that weird
posts - 187 , comments - 340 , trackbacks - 106

My Links

News

Twitter












Tag Cloud

Archives

Post Categories

Play

Work

Http Post in C#

Searched out on the internet and didn't really find anything that was horribly succinct, so I wrote this class for fun.  I had help from http://www.codeproject.com/cs/webservices/translation.asp.  I hope you enjoy!  Here's the code to call it:

PostSubmitter post=new PostSubmitter();
post.Url="http://seeker.dice.com/jobsearch/servlet/JobSearch";
post.PostItems.Add("op","100");
post.PostItems.Add("rel_code","1102");
post.PostItems.Add("FREE_TEXT","c# jobs");
post.PostItems.Add("SEARCH","");
post.Type=PostSubmitter.PostTypeEnum.Post;
string result=post.Post();

And here's the class:

using System;
using System.Text;
using System.IO;
using System.Web;
using System.Net;
using System.Collections.Specialized;

namespace Snowball.Common
{
/// <summary>
/// Submits post data to a url.
/// </summary>
public class PostSubmitter
{
/// <summary>
/// determines what type of post to perform.
/// </summary>
public enum PostTypeEnum
{
/// <summary>
/// Does a get against the source.
/// </summary>
Get,
/// <summary>
/// Does a post against the source.
/// </summary>
Post
}

private string m_url=string.Empty;
private NameValueCollection m_values=new NameValueCollection();
private PostTypeEnum m_type=PostTypeEnum.Get;
/// <summary>
/// Default constructor.
/// </summary>
public PostSubmitter()
{
}

/// <summary>
/// Constructor that accepts a url as a parameter
/// </summary>
/// <param name="url">The url where the post will be submitted to.</param>
public PostSubmitter(string url):this()
{
m_url=url;
}

/// <summary>
/// Constructor allowing the setting of the url and items to post.
/// </summary>
/// <param name="url">the url for the post.</param>
/// <param name="values">The values for the post.</param>
public PostSubmitter(string url, NameValueCollection values):this(url)
{
m_values=values;
}

/// <summary>
/// Gets or sets the url to submit the post to.
/// </summary>
public string Url
{
get
{
return m_url;
}
set
{
m_url=
value;
}
}
/// <summary>
/// Gets or sets the name value collection of items to post.
/// </summary>
public NameValueCollection PostItems
{
get
{
return m_values;
}
set
{
m_values=
value;
}
}
/// <summary>
/// Gets or sets the type of action to perform against the url.
/// </summary>
public PostTypeEnum Type
{
get
{
return m_type;
}
set
{
m_type=
value;
}
}
/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <returns>a string containing the result of the post.</returns>
public string Post()
{
StringBuilder parameters=
new StringBuilder();
for (int i=0;i < m_values.Count;i++)
{
EncodeAndAddItem(
ref parameters,m_values.GetKey(i),m_values[i]);
}
string result=PostData(m_url,parameters.ToString());
return result;
}
/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <param name="url">The url to post to.</param>
/// <returns>a string containing the result of the post.</returns>
public string Post(string url)
{
m_url=url;
return this.Post();
}
/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <param name="url">The url to post to.</param>
/// <param name="values">The values to post.</param>
/// <returns>a string containing the result of the post.</returns>
public string Post(string url, NameValueCollection values)
{
m_values=values;
return this.Post(url);
}
/// <summary>
/// Posts data to a specified url. Note that this assumes that you have already url encoded the post data.
/// </summary>
/// <param name="postData">The data to post.</param>
/// <param name="url">the url to post to.</param>
/// <returns>Returns the result of the post.</returns>
private string PostData(string url, string postData)
{
HttpWebRequest request=
null;
if (m_type==PostTypeEnum.Post)
{
Uri uri =
new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding =
new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else
{
Uri uri =
new Uri(url + "?" + postData);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "GET";
}
string result=string.Empty;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}
/// <summary>
/// Encodes an item and ads it to the string.
/// </summary>
/// <param name="baseRequest">The previously encoded data.</param>
/// <param name="dataItem">The data to encode.</param>
/// <returns>A string containing the old data and the previously encoded data.</returns>
private void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
{
if (baseRequest==null)
{
baseRequest=
new StringBuilder();
}
if (baseRequest.Length!=0)
{
baseRequest.Append("&");
}
baseRequest.Append(key);
baseRequest.Append("=");
baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
}
}
}

Print | posted on Friday, April 21, 2006 3:51 PM | Filed Under [ Work ]

Feedback

Gravatar

# re: Http Post in C#

Very useful, I too searched for how to do this nativly - I can't believe that .net dosnt have this as part of the WebRequest set of classes themselves!

Thanks!
5/4/2006 2:11 AM | JT
Gravatar

# re: Http Post in C#

Make sure that you have referenced the System.Web assembly, since that's where the HttpUtility class if found.

Right click on References, select Add Reference, and then select the System.Web assembly.

Robert
5/4/2006 11:19 AM | Robert May
Gravatar

# re: Http Post in C#

It all depends on what assembly contains the actual function. For example, if you wrote a dll, even though the dll was on your computer, you wouldn't be able to access the functions in it until you added it as a reference. System.Web contains the HttpUtility class, so unless you've included that assembly in your project, you won't have access to the class.
5/8/2006 4:40 AM | Robert May
Gravatar

# re: Http Post in C#

Maybe this is new in dot net 2.0? But http webrequest object can do this natively...

// Set the 'Method' property of the 'Webrequest' to 'POST'.
myHttpWebRequest.Method = "POST";
Console.WriteLine ("\nPlease enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri :");

// Create a new string object to POST data to the Url.
string inputData = Console.ReadLine ();


string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);
Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}", myHttpWebRequest.ContentLength);

// Close the Stream object.
newStream.Close ();
8/22/2006 11:49 PM | Jason Short
Gravatar

# re: Http Post in C#

Jason,

The code you supply as an example is basically the same code as what I've written.

The differences are the following:

This class makes it easy to add multiple items to the post.
This class encapsulates the functionality of sending a post and hides your need to know the details of how to do a post with web request.
This class does appropriate encoding of the input data.

Thanks for the input!

Robert
8/24/2006 11:24 AM | Robert May
Gravatar

# re: Http Post in C#

I am trying to submit a username and a pin for a an application via an asp.net page using this code, the kicker is is that it is being submitted to a jsp page that does a series of redirects i.e its submitted to init.jsp, which then goes to init2.jsp, is there anyway to relinquish control of the post after the initial submission and let the the browser control it?

What i am asking is, once I make the initial post is there anyway the browser can take over the rest, the asp.net app calls your code when user clicks a button
9/13/2006 7:43 PM | jad
Gravatar

# re: Http Post in C#

Jad,

You have to get the stream back from the source. Once you've received that stream, you can pass it back to the browser (i.e. Response.Write(stream)).

Since the initial post has been completed, the browser should take whatever is sent back to it and handle it the same way it would normally do so.

You may have to build urls and such inside of the result.

Basically, you should be able to just pass the results from the post directly back to the browser and it'll take over from there, assuming there aren't URL issues.
9/14/2006 6:28 AM | Robert May
Gravatar

# re: Http Post in C#

Robert....thanks for posting this code....it was exactly what I needed. I recently discovered the the Open Source VLC audio/video streamer/player has an interface that can be controlled via web posts.

I had embeded code into the Web Admin that GBPVR (Open Community Personal Video Recoding/Playing Sofware) uses to be able to stream video, audio and music from your PC to other PC's in the network or on the Internet. One of the pieces that was missing was the ability to control VLC from the users web browser since VLC was running in the background on the PC that hosted GBPVR.

Using this class I was able to integrate the controlling of VLC via the Web Admin in just a few minutes.

Much appreciated.

Thanks.

UncleJohnsBand
9/17/2006 4:30 PM | UncleJohnsBand
Gravatar

# re: Http Post in C#

Hey,

I was wondering if its possible to get the HTTP Code, i need to find out if it returns 200 or not. But im not sure how to go about this?
9/29/2006 3:17 PM | James
Gravatar

# re: Http Post in C#

The HttpWebResponse object has a StatusCode property that tells you the status code.

Be aware, however, that if it's a 500 or other error code, WebException will be thrown when you send the request to the server. Catch that exception, and then use the Response property on that exception to get the data that was returned and you can see what the server returned as well as check the StatusCode property to see exactly what caused the error (like 401, or whatever).

Robert
9/30/2006 5:37 AM | Robert May
Gravatar

# re: Http Post in C#

Thanks for this code!
Would it be possible to post a file with this?
10/25/2006 4:41 AM | alu
Gravatar

# re: Http Post in C#

Honestly, I don't know if it would work or not. It should, in theory, work, since file posts are just multi-part posts, but I'd have to experiment to see if it does or not.
10/25/2006 12:03 PM | Robert May
Gravatar

# re: Http Post in C#

I would be delighted if you could use your class to send files. :)
10/26/2006 3:02 AM | alu
Gravatar

# re: Http Post in C#

Is there a way to set an html input field's type as file?

i have this:
<INPUT type="file" name="file" tabIndex=8 size=36></INPUT>

and i need send this file with post using this class, so i need to set the type of the input

thanks,

12/13/2006 10:51 AM | leo
Gravatar

# re: Http Post in C#

Sending a file via post is a much more difficult problem. If I have the time, I'll code it up, however, the basics are as follows:

ContentType must be set to multipart/form-data with a boundary that will be inserted between each part of the web request.

Each part can have a content type associated with it.

For files, the type should be the specific type, or application/octet-stream if the type is unknown.

For an idea of how to do this, see http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm

Like I said, if I have time, I'll put out a class that would allow a file post to the server.

Robert
12/13/2006 1:31 PM | Robert May
Gravatar

# re: Http Post in C#

thanks for your reply.

i see this page and i could use it, but when i send the file, i believe that the file doesn´t arrive well.

the code to add a file is:

this.oPostData.Write(
Encoding.GetEncoding(1252).GetBytes("--" + this.cMultiPartBoundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + Key + "\" filename=\"" + new FileInfo(FileName).Name + "\"\r\n\r\n") );

oPostData is a BinaryWriter and

cMultiPartBoundary = "-----------------------------7cf2a327f01ae";

after that, this is the send of the data

Request.ContentType = "multipart/form-data; boundary=" + this.cMultiPartBoundary;

this.oPostData.Write( Encoding.GetEncoding(1252).GetBytes( "--" + his.cMultiPartBoundary + "\r\n" ) );

any idea why the file is not arrive well

sorry for my english

thanks
12/14/2006 5:48 AM | leo
Gravatar

# re: Http Post in C#

I think that the reason why the file isn't getting there is because it's never being sent. The code you list above doesn't actually contain anything that encodes the file and sends it.

Something like (I'm just writing this off the cuff, so it's probably not syntactically correct):

BinaryReader reader=new BinaryReader;
byte[] bytes=new byte[reader.length];
reader.readtoend(bytes);
//write out your boundary and header information
oPostData.Write(bytes);
12/14/2006 9:16 AM | Robert May
Gravatar

# re: Http Post in C#

Thanks for this code, a very useful wrapping around the HttpWebRequest object. I have discovered a bug though, that you may want to fix.

The problem is that ContentLength will be incorrect if the posted data contains multibyte characters (we're using UTF8 after all).

This is a more correct code for PostData():



//request.ContentLength = postData.Length;

UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);

// Sett contentlength to the number of bytes to send.
// NOTE: postData.Length and bytes.Length are not necessarily equal since
// some characters are represented by several bytes in UTF8.
request.ContentLength = bytes.Length;

using (Stream writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
1/24/2007 6:32 AM | Emil Astrom
Gravatar

# re: Http Post in C#

Awesome. Thanks for pointing it out. I'll update the code to show the change as soon as I get a chance.

One more reason why code reviews are essential. :)

Robert
1/24/2007 6:43 AM | Robert May
Gravatar

# re: Http Post in C#

The code is great.
I don't know how to use it for checkbox fields. THis is a hard question. I have been looking long for an answer and not found one. I greatly apreaciate any hint.


What are the name=value pairs for checkbox fields that are sent with POST? thnkx

So you have <input type="checkbox" value="myvalue" checked>
how do you specify wich checkbox and if it is checked or not. ?
2/14/2007 1:19 PM | paul
Gravatar

# re: Http Post in C#

To send checkbox values set the name to the name of the checkbox and the value to "on" for checked or "off" for not checked.

This can be a bit trickier when you're submitting the values for multiple checkboxes.

A good way to find out what needs to be sent is to set up a test page in IIS, create a test form in HTML, and then submit the form to IIS and see what is passed to the server. Then you simply need to replicate that submission in the name value pairs that you submit.

For more information on HTML forms, see http://www.w3.org/TR/html4/interact/forms.html

Robert
2/16/2007 5:23 AM | Robert May
Gravatar

# re: Http Post in C#

Hello.

First great work about this code.

If you will have some extra time, can you write code for posting files?

2/20/2007 2:30 PM | faca5
Gravatar

# re: Http Post in C#

It's on the list. Hopefully I'll have some time!
2/20/2007 3:19 PM | Robert May
Gravatar

# re: Http Post in C#

Meybe this useful?
www.codeproject.com/useritems/multipart_request_C_.asp

I need example which work! :)
2/21/2007 3:54 AM | faca5
Gravatar

# re: Http Post in C#

This is a great post. Thanks for this. But i need to be able to also read xml data that comes back in a http post. Does anyone have any examples for this?

Thanks
Deepa.
2/22/2007 3:12 PM | Deepa
Gravatar

# re: Http Post in C#

Hi,
thank you for the code - do you know of a way to open the POST request in a browser? In a GET request it is easy you just run process.start(url) how can it be done in POST?
do you have a sample or a link for that?
Thanks
Inbal
3/4/2007 10:35 PM | Inbal
Gravatar

# re: Http Post in C#

For that, you're looking at automating the IE Browser. You can do this either with the Microsoft Browser Control, or you can hit it directly using the AxBrowser control through interop.

It's quite a bit harder than this post example.

Robert
3/5/2007 7:12 AM | Robert May
Gravatar

# re: Http Post in C#

Hi. Your code can only send string parameters via the POST. Is there any way which I can send a whole value object (an object with different types of attributes) via the POST? Thanks.
3/15/2007 7:29 PM | Alvin
Gravatar

# re: Http Post in C#

Hey man,

I was hoping to adapt your code to try it out with a servlet.Its for a college project and this is a big stumbling block that I just cant get past.I cant seem to get it to work no matter what I try.

on the servlet page the

form name ="my form"
form action ="demo1_res"

there is a text input

name ="msisdn0"

there is a submit button

name="send"

value="SEND"

and finally there is

onclick="parent.infoframe.location='info';return true;"

Do I just plug these values into like this??

EG:
post.PostItems.Add("msisdn0","1234567");
post.PostItems.Add("send","SEND");
post.PostItems.Add("action","demo1_res");
post.PostItems.Add("name","my form");

Id really appreciate your advice on this.

Im dying to know how I can do it
4/4/2007 9:27 AM | dub
Gravatar

# re: Http Post in C#

You're mixing client side code (onclick) with stuff that gets sent back to the server.

you should be able to plug them in as you described.

This code is for something that would run inside of a .net application.

More description of the problem you're having would help me to give you a better answer.
4/4/2007 9:45 AM | Robert May
Gravatar

# re: Http Post in C#

Heya, thanks for the reply.

Well I've got a servlet application.It is running on apache tomcat. If opened normally in a browser you enter a number in a textbox and press submit. You would then be taken to a page where the result is.

This is the source of the page
************************************
<html><head><META HTTP-EQUIV='PRAGMA' CONTENT='NO-CACHE'><title>Example 1, MT-LR</title><link href="style.css" type="text/css" rel="stylesheet"></head><body><H1>MT-LR</H1><form name="myForm" action="demo1_res" method="post"><table border="0" cellpadding="5" cellspacing="0"><tr><td>MSISDN</td><td><input type="text" name="msisdn0" size="20"/></td></tr><tr><td class="tGray">
**********************************************

What im trying to do is get c# to "enter the number" and "press the submit button"

It seems to me that the servlet isn't receiving the post request.

If theres any way I can describe the problem please let me know.

(p.s: i'm new to c# so my vocabulary isn't great)

Cheers
Dub

4/4/2007 2:31 PM | dub
Gravatar

# re: Http Post in C#

Also I forgot to mention that the c# code is running from an aspx page. I just have it in the "onPageLoad" function for the moment for testing.

4/4/2007 2:36 PM | dub
Gravatar

# re: Http Post in C#

it worked It worked it worked !!!!!

Thankyou so much!! :-)

Ive been trying to figure this out for days
xxx
4/4/2007 3:09 PM | dub
Gravatar

# re: Http Post in C#

What you'll need to do is provide your own "browing" functionality. You'll have to submit a new post or request to the page that they redirect you too.

You may want to look into the WebBrowser control. It has this functionality built in.
4/5/2007 11:56 AM | Robert May
Gravatar

# re: Http Post in C#

This class is cool. Quite usefull. I'm running it in a console application, Anyone know how to launch IE with the results of the:
"string result=post.Post();"
4/10/2007 10:14 AM | Eric
Gravatar

# re: Http Post in C#

Easiest way? Write out the contents to a temp file with a .html extension and then launch IE with that url in the browser window.

Harder way, Create a new instance of the AxWebBrowser control and load the IHTMLDom with the results of the browse.
4/10/2007 10:32 AM | Robert May
Gravatar

# i'm lost! =(

i tried to I had help from your code but i failed! i'm trying to make a form sender from c# to any form script (php, asp etc.)
for example; think that i've a user name chack script in php when you send a form GET request from a web page you'll get the answer if the username is registered.. Now i wanna send this form GET request from my c# project.. but i'm lost =(
4/21/2007 5:13 AM | DaRKMaN
Gravatar

# re: Http Post in C#

Can you upload project? All files?
4/29/2007 6:12 AM | faca5
Gravatar

# re: Http Post in C#

I've achieved the same result as this PostSubmitter class with the follow code

WebClient oClient = new WebClient();
oClient.QueryString.Add("login", msUser);
oClient.QueryString.Add("password", msPassword);
msConnect=oClient.DownloadString(msSite);

But this is not post.
WebClient in C# allow in addition to download files from the web very easilly.

Regards
6/24/2007 8:09 PM | HSaturn
Gravatar

# re: Http Post in C#

I'm interested how "dub" got his POST to a java servlet to work as I have the same issue.
7/10/2007 9:50 AM | Chris Gallucci
Gravatar

# re: Http Post in C#

Posting to a servlet is the same as posting to any other web resource. They still have to abide by the same http GET, READ, CREATE, DELETE rules as any other mechanism. However, you may have to be a smarter client and understand what they send back to you better. Analyze the results and see if they're sending back what you expect. Also, understand what it is that they're requesting. You'll need to know their parameters, cookies, and other information.

Good luck!
7/10/2007 9:55 AM | Robert May
Gravatar

# re: Http Post in C#

HI Mike, I'm trying to send a TXT File into a hTTPS URL with C#, but i'm not a senior Developer, it's new for me.
Someone has a example code or sth please..it's emergency ;;;
I'm LOST
8/2/2007 2:37 AM | hichem
Gravatar

# re: Http Post in C#

Hi Guys (and girls),
seems I got stuck with the code as I try something similar than hichem. I would like to POST an image file and a txt file together to a server. Any idea what needs to be enhanced in the class to make this work?
In a standard HTTP POST formular it is type=file and usually get's encoded etc automatically. Is this the same here?

Thanks
10/6/2007 10:07 AM | Dietmar
Gravatar

# re: Http Post in C#

Hey Pls can you help me..your code looks great.but for me I am getting this "remote server name could not be resolved" error can you help me on this?
10/24/2007 8:55 AM | Priti
Gravatar

# re: Http Post in C#

I'd like to know if there's a way to redirect the flow to the remote site. I'm trying to use this code to do a POST to a credit card on-line validation system. Once I do the POST, the remote site continues the process and finally it will return to the original calling site. Is there a way to do that POST and at the same time redirect to the "posted" site?
11/14/2007 9:42 AM | George
Gravatar

# re: Http Post in C#

Thanks for the post. I used this code in my project now listed on CodePlex, TumblrAPI.NET: www.codeplex.com/tumblr/
1/26/2008 11:08 AM | madkidd
Gravatar

# Post to secured area

Great code -

Do you know how to modify it to allow posting login information to one page, saving the cookie information, and then posting to another page?

Thanks,

Andrew
2/26/2008 8:58 PM | Andrew
Gravatar

# re: Http Post in C#

hi,

i want to pass the username and password from my asp.net application to gmail login page. is it possible? give me the right and appropriate code....
3/3/2008 2:57 AM | nainar
Gravatar

# re: Http Post in C#

the campact framework have not

System.Web;

what class can rather than this System.Web?
4/13/2008 12:48 AM | angus
Gravatar

# re: Http Post in C#

Thank you very much.
But could you tell me how Rapidshare uses Http POST to transfer files? I want to make a free user downloader app which will intercept IE's default dwnld mgr in WebBrowser control. So how do I do it?

Any help please.
5/5/2008 4:01 AM | Anindya Chatterjee
Gravatar

# re: Http Post in C#

Nice helper class ! good job and Thanks for sharing it !
6/15/2008 11:08 AM | paslatek
Gravatar

# re: Http Post in C#

Can i get last valid credit card transation of a user by using our merchat login and password using the same standard of coding.
6/16/2008 2:03 AM | Jose
Gravatar

# Help me...!!!!

Can i get last valid credit card transation of a user by using our merchat login and password using the same standard of coding.
6/16/2008 2:05 AM | Jose
Gravatar

# re: Http Post in C#

VERY HELP FULL POST.
THANK U SO MUCH.
6/30/2008 12:20 PM | Naresg Thandu
Gravatar

# re: Http Post in C#

Very useful utility class - thanks a bunch!
7/26/2008 12:39 AM | Ian
Gravatar

# re: Http Post in C#

Great class. I need to pass a username and password to the site I am hitting.

Similar VB code would be;
Set objRequest = CreateObject("Microsoft.XMLHTTP")
objRequest.setRequestHeader "Authorization", "Basic " & Base64Encode(X_USERNAME & ":" & X_PASSWORD)

Any ideas??

Thanks a million
9/11/2008 12:46 PM | smullo
Gravatar

# re: Http Post in C#

Very nice app. There are not many times when I can take something from the web and use it immediately, i was up and running within 5 minutes and I didnt have to do crap.

THANKS!
1/13/2009 2:25 PM | eyeorg
Gravatar

# re: Http Post in C#

Im add the try for Exception. Thx for the class man !

private string PostData(string url, string postData)
{
HttpWebRequest request = null;
if (m_type == PostTypeEnum.Post)
{
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else
{
Uri uri = new Uri(url + "?" + postData);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
}
string result = string.Empty;

try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
}
catch (System.Net.WebException e)
{
result = e.Status.ToString();
}
return result;
}
1/13/2009 6:25 PM | Alexo
Gravatar

# Wat about js functions in the form?

Hi.

Thanks alot for such an informative post... I tried searching alot, but finally found your code..

My need is to call the javascript method to post the form..I have tried this code to submit a php file which straightaway sends emails to me, but now my need is not to call the php directly, but to call the function..

Also.. the result string contains the webpage and not the eception if any.. how can i get to kno what failed my call to the webform.

How can i do that..
2/4/2009 4:07 AM | Munish Sethi
Gravatar

# re: Http Post in C#

Hi.
thanks for the script.. We can submit normal forms using this script..

But how can we submit such forms on the web, which needs login.. Say for example a social blog messaging needs login first. I tried this script to submit a messaging form on one of the social blog, but it never submits the message, maybe i need to login first..

How can i really achieve this. i mean first hitting the login action and then sending message via code only.

munishsethi777@yahoo.com

Munish.
2/4/2009 9:28 PM | Munish Sethi
Gravatar

# re: Http Post in C#

Hi,
I use the process to post data in classic ASP, I get data properly posted to classic asp but if some one click back button of borwser it does not take to the proper aspx page it takes to intermediate page which was created using above process ny help how to clear back button process and take user to proper aspx page.

Thanks
Raj
2/26/2009 2:56 PM | Raj
Gravatar

# re: Http Post in C#

hi !

maybe am I stupid but I have no redirection using this code.
I use it on a linkbutton event, the code on my url page is executed but I stay on the current page and there is no redirection to the url.
Do I forget something ?
3/12/2009 1:46 PM | oliv
Gravatar

# re: Http Post in C#

Hey!!

Very good post!!

It really works, but to connect against HTTPS, i needed to use the certification and policy code posted in http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/

very good anyway

Thanks!!
3/13/2009 6:20 PM | Joel
Gravatar

# re: Http Post in C#

Thank's class RULEZZ!
3/31/2009 3:26 AM | Dave
Gravatar

# re: Http Post in C#

thanks a lot for this post. :)
4/17/2009 10:45 PM | tk
Gravatar

# re: Http Post in C#

Thank U for the class

Very Useful !!
6/8/2009 3:29 AM | Ofir
Gravatar

# re: Http Post in C#

Hi I am having some trouble uploading a file from c#.net app to servlet! I want to upload the file and also add some parameters to the request. At the moment I am using WebClient.FileUpload(uri, "POST", file); I have added a querystring to the uri which contains all the necessary parameters.

On the server side I am able to access the querystring of the request and I can access the content of the file, however, the get and the post method of my servlet are being invoked. I cannot understand why as it seems to be a simple process of passing the parameters in the uri and then using fileUpload to upload the file.

I really need help with this - any suggestions as to why this is happening?
7/1/2009 5:58 AM | EK
Gravatar

# re: Http Post in C#

Hey,

Can you please help for, how to POST the WML pge ("WAP PUSH") using HTTP POST method?

This is for the WAP browser on my mobile phone.

Thank you.
7/7/2009 11:44 PM | Ashlesh
Gravatar

# re: Http Post in C#

When i try to POST html code i've got an error.(500).
Any ideas??
7/16/2009 8:15 AM | Luca
Gravatar

# re: Http Post in C#

Resolved..... The HTML must be URLENCODED.
Your class is Fantastic....
Thx
7/17/2009 1:58 AM | Luca
Gravatar

# re: Http Post in C#

Great!

I haven't tested it yet but allready added it as code snippets.

Will love it!
7/27/2009 6:24 PM | James
Gravatar

# re: Http Post in C#

How can I use this class if I want to redirect to that page whith my Post() arguments? That page where I want to redirect needs parameters in POST method and that page have own results....
7/31/2009 6:01 AM | Linker
Gravatar

# re: Http Post in C#

First of all thanks for really nice code.

I have got one problem.
I am using post with some parameters. But the code was throwing 401 exception. I covered that with try catch. But problem is in order to complete the post I need to post multiple times with connections KEEPING ALIVE.
What I need to do in order to achieve these results?
8/14/2009 5:12 AM | GNome
Gravatar

# re: Http Post in C#

How can this class be used to re-direct to the page you are posting to? I am trying to use this to construct a Paypal post and re-direct to paypal. I am getting the HMTL code back from the post, but how do I redirect to that page instead of getting it back to me.
9/1/2009 10:10 AM | Adrian
Gravatar

# re: Http Post in C#

hi,thanks for your useful code!
9/15/2009 2:05 AM | samaneh
Gravatar

# re: Http Post in C#, please help me

can i use this to post data from my c# windows app form to php page,

<input size="26" name="name_web" maxlength="20" onkeyup="return ismaxlength(this)" value="" type="text">

i want to post data to the value and name_web is the name of the varaible

9/26/2009 9:57 AM | Elhelow
Gravatar

# re: Http Post in C#

Any thoughts on why this wont work? Doesn't return any errors. It just doesn't seem to work

private void button11_Click(object sender, EventArgs e)
{

WebRequest request = WebRequest.Create("http://www.xeroghz.com/friends_list_update.php");
request.Method = "POST";

//MessageBox.Show("ID=" + lblID.Text + "&appcount=" + Convert.ToString(iAppCount) + "&friends=" + sFlist);
string postData = "ID=503011512&appcount=0&friends=test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

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.
MessageBox.Show(((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.
MessageBox.Show(responseFromServer);


// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();

}
9/29/2009 9:21 PM | Mitch
Gravatar

# re: Http Post in C#

Very useful, thank you!
12/19/2009 2:55 PM | opatut
Gravatar

# re: Http Post in C#

Thank you the code is working but I have a question .

I have 2 pages (the first to send the information in the form ) and ( the second one to receive info then check with DB if it is true or not ) ,

sometimes there is an error ( internal server error 500 ) . Can I know why this error is occure ? Is it regarding the (data size ) ( or the DB in the second page )
or what ?
please help me ?
1/12/2010 7:30 AM | Sara
Gravatar

# re: Http Post in C#

Thank you so much for this class. It definitely made things simpler for me and got my program up and running as i intended. Many thanks!
1/22/2010 6:05 AM | Trevor
Gravatar

# re: Http Post in C#

Hi!
Thank you for this!
Other sense :
I try to upload a file via a normal HTML form and then parse post data in C#...
I manage to get a string like :
-----------------------------14018187879905 Content-Disposition: form-data; name="myfile"; filename="nietzsche-.jpg" Content-Type: image/jpeg �����JFIF���d�...

But how can I get the exact file as a char or byte array?
I post this here because u guys look like u know a lot about it :)
Thanks in advance!
1/28/2010 3:57 AM | PittMarson
Gravatar

# re: Http Post in C#

Hi, I can't seem to get this to work. I've tried it on a few websites.

post.Url = "http://www.localjobhq.com/";
post.PostItems.Add("job_name", "food");
post.PostItems.Add("submit", " ");

there isn't a name for the submit button, so i tried a few things. Does anyone know what i am doing wrong?
2/12/2010 5:41 PM | Jin
Gravatar

# A simplified version

This is simplified version of the class.

using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace WebSumit
{
public enum MethodType
{
POST = 0,
GET = 1
}

public class WebSumitter
{

public WebSumitter()
{
}

public string Submit(string URL, Dictionary<string, string> Parameters, MethodType Method)
{
StringBuilder _Content = new StringBuilder();
string _ParametersString = "";

// Prepare Parameters String
foreach (KeyValuePair<string, string> _Parameter in Parameters)
{
_ParametersString = _ParametersString + (_ParametersString != "" ? "&" : "") + string.Format("{0}={1}",_Parameter.Key, _Parameter.Value);
}

// Initialize Web Request
HttpWebRequest _Request = (HttpWebRequest)WebRequest.Create(URL);
// Request Method
_Request.Method = Method == MethodType.POST ? "POST" : (Method == MethodType.GET ? "GET" : "");
// Send Request
using (StreamWriter _Writer = new StreamWriter(_Request.GetRequestStream(), Encoding.UTF8))
{
_Writer.Write(_ParametersString);
}
// Initialize Web Response
HttpWebResponse _Response = (HttpWebResponse)_Request.GetResponse();
// Get Response
using (StreamReader _Reader = new StreamReader(_Response.GetResponseStream()))
{
_Content.Append(_Reader.ReadToEnd());
}

return _Content.ToString();
}

}
}
2/14/2010 11:54 PM | denver320
Gravatar

# re: Http Post in C#

Thanks for the amazing tutorial/class post.
I'm just wondering if you have to type in %40 for the @ sign
3/7/2010 8:29 PM | Joshua Xu
Gravatar

# Http Post in C#

Thank you very much... :)
4/11/2010 1:24 PM | Niyati
Gravatar

# re: Http Post in C#

if help this code add cookie (i use from a webBrowser, myCookie =browser.Document.Cookie)
HttpWebRequest request ...
request.CookieContainer = new CookieContainer();
request.CookieContainer.SetCookies(new Uri(postUrl), myCookie);
4/12/2010 4:59 AM | Teutonico
Gravatar

# re: Http Post in C#

Thanks. This works great!
4/23/2010 2:27 PM | Cory
Gravatar

# re: Http Post in C#

Great job!

Thank's
6/23/2010 3:27 AM | josejuan
Gravatar

# re: Http Post in C#

1 suggestion

( new PostSubmitter(
myUrl,
new System.Collections.Specialized.NameValueCollection() {
{ "name1", value1 },
{ "name2", value2 },
...
},
PostSubmitter.PostTypeEnum.Post
) ).Post()

Long live to Haskell!!!
6/23/2010 3:33 AM | josejuan
Gravatar

# re: Http Post in C#

Hey thank you very much! This is simple code fine works, good ideas
7/8/2010 12:00 AM | Rimon Salmonik
Gravatar

# re: Http Post in C#

ok I can now send GET an POST http requests, but how to send PUT or DELETE http request?
7/29/2010 11:20 AM | InTeGer
Gravatar

# Dont download images

Thanks for the nice class. I have a question.

When posting the POST data to the url, I do not want to download/process the images (to save bandwidth) in the result page. How can I do this?
7/29/2010 1:01 PM | selwonski
Gravatar

# re: Http Post in C#

You have no idea how much grief you saved me with this class. THANK YOU!!!!
2/24/2011 12:09 PM | Truncated CoDr
Gravatar

# re: Http Post in C#

the code is Tooooooooooooooooooooooooo long just for a simple task
3/29/2011 7:54 AM | nq
Gravatar

# re: Http Post in C#

thanks for the code, you saved me from having to write something similar
4/24/2011 4:01 PM | Dave
Gravatar

# re: Http Post in C#

Hi
I want to send bunch of folders from one server to another server using HTTPPOST and same folder structure should be on destination server
Can any one Please guide me if you have any idea how to achive this using HTTPPOST

Thanks in Advance
6/20/2011 1:11 AM | Ranjeet Kuimar
Gravatar

# re: Http Post in C#

I'm having a problem with the code, maybe you guys can help,

i have this textbox
<asp:TextBox ID="txtAmount" runat="server"></asp:TextBox>
this gets the amount to send to paypal, then i have a button

<asp:Button ID="btnPaymentPaypal" runat="server" Text="Pay via PayPal" onclick="btnPaymentPaypal_Click"/> this triggers the event on the code:

using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KOM1finance.SupportClasses;

namespace KOM1finance.secured.CustTermination.PayPal
{
public partial class PayPalPayment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}

protected void btnPaymentPaypal_Click(object sender, EventArgs e)
{
PostSubmitter post = new PostSubmitter();
post.Url = "http://sandbox.paypal.com/cgi-bin/webscr";
post.PostItems.Add("cmd", "_xclick");
post.PostItems.Add("business", "<%= ConfigurationManager.AppSettings['PayPalUsername'] %>");
post.PostItems.Add("amount", "amount.Text.ToString()");
post.PostItems.Add("return", "http://localhost:3970/CPanel/CustTermination/PayPal/ThankYou.aspx");
post.PostItems.Add("date", "Registration started: <%= DateTime.Now.ToString() %>");
post.PostItems.Add("submit", "");
post.Type = PostSubmitter.PostTypeEnum.Post;
string result = post.Post();
}

}
}

then comes the error on the class that you have here on line 160:

Server Error in '/' Application.

The remote certificate is invalid according to the validation procedure.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

Source Error:


Line 158:}
Line 159:string result=string.Empty;
Line 160:using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
Line 161:{
Line 162:using (Stream responseStream = response.GetResponseStream())

Source File: C:\Users\Nica1\Documents\Visual Studio 2010\Projects\kom1 grande\KOM1finance\SupportClasses\PostSubmitter.cs Line: 160

any ideas?

7/7/2011 4:50 PM | Ron Eskinder
Gravatar

# I cannot seem to find a reference for System.Web

Developing/prototyping from a console application under Visual Studio.Net 2010. Attempted to add a reference to System.Web to the project from the .Net tab and Browse tab... Both failed. I did find the 4.0 version System.Web under C:\Windows\Microsoft.Net\Framework64\v4.0.30319\System.Web.dll to this give a warning icon in the IDE.... I've seen some reference to problems with this dll out on the web but no solutions.

Thanks Guys and btw thanks for posting this snippet. It's going to be useful
8/8/2011 9:27 AM | Gregg
Gravatar

# Found reference

Seems that the frame work of the application created at the start of the IDE is the one used to find a reference by framework version. Right clicking the "Solution" references will give you a list of references for the current frame work version. If you use the "Object Browser" to add the reference button you can select the framework that you wish to use. 4.0 gives an error icon. If 3.5 is used frame work version 2.0 is added. This is just a heads or annotating some of the difficulties mentioned on the web. But the right clicking on the "Reference" portion of the solution may not get you what you want. At any rate up and flying .... well at least waddling :). Thanks guys for all the info and a great post.
Gregg
8/8/2011 10:44 AM | Gregg
Gravatar

# re: Http Post in C#

Your code worked great, Thanks for the help
8/8/2011 10:55 AM | frankp
Gravatar

# re: Http Post in C#

With POST I get from sample code above 500er error from dice! Any ideas? with GET works fine, but what is wrong on POST?
10/20/2011 1:22 AM | Volker
Gravatar

# re: Http Post in C#

Your code works really great.

I'm SOOOOOOOOOOOOO using it on every project.
2/8/2012 2:14 AM | Gunbilegt
Gravatar

# re: Http Post in C#

Works fine but only at .NET v2 ? At v4 I can't System.Web in the list of .NET references.
3/8/2012 10:26 AM | Antilles
Gravatar

# re: Http Post in C#

For C# generics refer
http://just-dotnet.blogspot.in/2012/06/c-generics-introduction.html
7/15/2012 2:16 PM | Ramesh
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

Powered by: