Geeks With Blogs

The Life and Times of a Dev Yes, we're really that weird

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));
}
}
}

Posted on Friday, April 21, 2006 3:51 PM | Back to top


Comments on this post: Http Post in C#

# re: Http Post in C#
Requesting Gravatar...
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!
Left by JT on May 04, 2006 2:11 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on May 04, 2006 11:19 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Robert May on May 08, 2006 4:40 AM

# re: Http Post in C#
Requesting Gravatar...
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 ();
Left by Jason Short on Aug 22, 2006 11:49 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on Aug 24, 2006 11:24 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by jad on Sep 13, 2006 7:43 PM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Robert May on Sep 14, 2006 6:28 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by UncleJohnsBand on Sep 17, 2006 4:30 PM

# re: Http Post in C#
Requesting Gravatar...
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?
Left by James on Sep 29, 2006 3:17 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on Sep 30, 2006 5:37 AM

# re: Http Post in C#
Requesting Gravatar...
Thanks for this code!
Would it be possible to post a file with this?
Left by alu on Oct 25, 2006 4:41 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Robert May on Oct 25, 2006 12:03 PM

# re: Http Post in C#
Requesting Gravatar...
I would be delighted if you could use your class to send files. :)
Left by alu on Oct 26, 2006 3:02 AM

# re: Http Post in C#
Requesting Gravatar...
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,

Left by leo on Dec 13, 2006 10:51 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on Dec 13, 2006 1:31 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by leo on Dec 14, 2006 5:48 AM

# re: Http Post in C#
Requesting Gravatar...
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);
Left by Robert May on Dec 14, 2006 9:16 AM

# re: Http Post in C#
Requesting Gravatar...
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);
}
Left by Emil Astrom on Jan 24, 2007 6:32 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on Jan 24, 2007 6:43 AM

# re: Http Post in C#
Requesting Gravatar...
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. ?
Left by paul on Feb 14, 2007 1:19 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on Feb 16, 2007 5:23 AM

# re: Http Post in C#
Requesting Gravatar...
Hello.

First great work about this code.

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

Left by faca5 on Feb 20, 2007 2:30 PM

# re: Http Post in C#
Requesting Gravatar...
It's on the list. Hopefully I'll have some time!
Left by Robert May on Feb 20, 2007 3:19 PM

# re: Http Post in C#
Requesting Gravatar...
Meybe this useful?
www.codeproject.com/useritems/multipart_request_C_.asp

I need example which work! :)
Left by faca5 on Feb 21, 2007 3:54 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Deepa on Feb 22, 2007 3:12 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Inbal on Mar 04, 2007 10:35 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Robert May on Mar 05, 2007 7:12 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Alvin on Mar 15, 2007 7:29 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by dub on Apr 04, 2007 9:27 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Robert May on Apr 04, 2007 9:45 AM

# re: Http Post in C#
Requesting Gravatar...
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

Left by dub on Apr 04, 2007 2:31 PM

# re: Http Post in C#
Requesting Gravatar...
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.

Left by dub on Apr 04, 2007 2:36 PM

# re: Http Post in C#
Requesting Gravatar...
it worked It worked it worked !!!!!

Thankyou so much!! :-)

Ive been trying to figure this out for days
xxx
Left by dub on Apr 04, 2007 3:09 PM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Robert May on Apr 05, 2007 11:56 AM

# re: Http Post in C#
Requesting Gravatar...
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();"
Left by Eric on Apr 10, 2007 10:14 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Robert May on Apr 10, 2007 10:32 AM

# i'm lost! =(
Requesting Gravatar...
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 =(
Left by DaRKMaN on Apr 21, 2007 5:13 AM

# re: Http Post in C#
Requesting Gravatar...
Can you upload project? All files?
Left by faca5 on Apr 29, 2007 6:12 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by HSaturn on Jun 24, 2007 8:09 PM

# re: Http Post in C#
Requesting Gravatar...
I'm interested how "dub" got his POST to a java servlet to work as I have the same issue.
Left by Chris Gallucci on Jul 10, 2007 9:50 AM

# re: Http Post in C#
Requesting Gravatar...
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!
Left by Robert May on Jul 10, 2007 9:55 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by hichem on Aug 02, 2007 2:37 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Dietmar on Oct 06, 2007 10:07 AM

# re: Http Post in C#
Requesting Gravatar...
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?
Left by Priti on Oct 24, 2007 8:55 AM

# re: Http Post in C#
Requesting Gravatar...
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?
Left by George on Nov 14, 2007 9:42 AM

# re: Http Post in C#
Requesting Gravatar...
Thanks for the post. I used this code in my project now listed on CodePlex, TumblrAPI.NET: www.codeplex.com/tumblr/
Left by madkidd on Jan 26, 2008 11:08 AM

# Post to secured area
Requesting Gravatar...
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
Left by Andrew on Feb 26, 2008 8:58 PM

# re: Http Post in C#
Requesting Gravatar...
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....
Left by nainar on Mar 03, 2008 2:57 AM

# re: Http Post in C#
Requesting Gravatar...
the campact framework have not

System.Web;

what class can rather than this System.Web?
Left by angus on Apr 13, 2008 12:48 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Anindya Chatterjee on May 05, 2008 4:01 AM

# re: Http Post in C#
Requesting Gravatar...
Nice helper class ! good job and Thanks for sharing it !
Left by paslatek on Jun 15, 2008 11:08 AM

# re: Http Post in C#
Requesting Gravatar...
Can i get last valid credit card transation of a user by using our merchat login and password using the same standard of coding.
Left by Jose on Jun 16, 2008 2:03 AM

# Help me...!!!!
Requesting Gravatar...
Can i get last valid credit card transation of a user by using our merchat login and password using the same standard of coding.
Left by Jose on Jun 16, 2008 2:05 AM

# re: Http Post in C#
Requesting Gravatar...
VERY HELP FULL POST.
THANK U SO MUCH.
Left by Naresg Thandu on Jun 30, 2008 12:20 PM

# re: Http Post in C#
Requesting Gravatar...
Very useful utility class - thanks a bunch!
Left by Ian on Jul 26, 2008 12:39 AM

# re: Http Post in C#
Requesting Gravatar...
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
Left by smullo on Sep 11, 2008 12:46 PM

# re: Http Post in C#
Requesting Gravatar...
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!
Left by eyeorg on Jan 13, 2009 2:25 PM

# re: Http Post in C#
Requesting Gravatar...
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;
}
Left by Alexo on Jan 13, 2009 6:25 PM

# Wat about js functions in the form?
Requesting Gravatar...
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..
Left by Munish Sethi on Feb 04, 2009 4:07 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Munish Sethi on Feb 04, 2009 9:28 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Raj on Feb 26, 2009 2:56 PM

# re: Http Post in C#
Requesting Gravatar...
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 ?
Left by oliv on Mar 12, 2009 1:46 PM

# re: Http Post in C#
Requesting Gravatar...
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!!
Left by Joel on Mar 13, 2009 6:20 PM

# re: Http Post in C#
Requesting Gravatar...
Thank's class RULEZZ!
Left by Dave on Mar 31, 2009 3:26 AM

# re: Http Post in C#
Requesting Gravatar...
thanks a lot for this post. :)
Left by tk on Apr 17, 2009 10:45 PM

# re: Http Post in C#
Requesting Gravatar...
Thank U for the class

Very Useful !!
Left by Ofir on Jun 08, 2009 3:29 AM

# re: Http Post in C#
Requesting Gravatar...
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?
Left by EK on Jul 01, 2009 5:58 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Ashlesh on Jul 07, 2009 11:44 PM

# re: Http Post in C#
Requesting Gravatar...
When i try to POST html code i've got an error.(500).
Any ideas??
Left by Luca on Jul 16, 2009 8:15 AM

# re: Http Post in C#
Requesting Gravatar...
Resolved..... The HTML must be URLENCODED.
Your class is Fantastic....
Thx
Left by Luca on Jul 17, 2009 1:58 AM

# re: Http Post in C#
Requesting Gravatar...
Great!

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

Will love it!
Left by James on Jul 27, 2009 6:24 PM

# re: Http Post in C#
Requesting Gravatar...
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....
Left by Linker on Jul 31, 2009 6:01 AM

# re: Http Post in C#
Requesting Gravatar...
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?
Left by GNome on Aug 14, 2009 5:12 AM

# re: Http Post in C#
Requesting Gravatar...
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.
Left by Adrian on Sep 01, 2009 10:10 AM

# re: Http Post in C#
Requesting Gravatar...
hi,thanks for your useful code!
Left by samaneh on Sep 15, 2009 2:05 AM

# re: Http Post in C#, please help me
Requesting Gravatar...
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

Left by Elhelow on Sep 26, 2009 9:57 AM

# re: Http Post in C#
Requesting Gravatar...
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();

}
Left by Mitch on Sep 29, 2009 9:21 PM

# re: Http Post in C#
Requesting Gravatar...
Very useful, thank you!
Left by opatut on Dec 19, 2009 2:55 PM

# re: Http Post in C#
Requesting Gravatar...
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 ?
Left by Sara on Jan 12, 2010 7:30 AM

# re: Http Post in C#
Requesting Gravatar...
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!
Left by Trevor on Jan 22, 2010 6:05 AM

# re: Http Post in C#
Requesting Gravatar...
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!
Left by PittMarson on Jan 28, 2010 3:57 AM

# re: Http Post in C#
Requesting Gravatar...
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?
Left by Jin on Feb 12, 2010 5:41 PM

# A simplified version
Requesting Gravatar...
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();
}

}
}
Left by denver320 on Feb 14, 2010 11:54 PM

# re: Http Post in C#
Requesting Gravatar...
Thanks for the amazing tutorial/class post.
I'm just wondering if you have to type in %40 for the @ sign
Left by Joshua Xu on Mar 07, 2010 8:29 PM

# Http Post in C#
Requesting Gravatar...
Thank you very much... :)
Left by Niyati on Apr 11, 2010 1:24 PM

# re: Http Post in C#
Requesting Gravatar...
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);
Left by Teutonico on Apr 12, 2010 4:59 AM

# re: Http Post in C#
Requesting Gravatar...
Thanks. This works great!
Left by Cory on Apr 23, 2010 2:27 PM

# re: Http Post in C#
Requesting Gravatar...
Great job!

Thank's
Left by josejuan on Jun 23, 2010 3:27 AM

# re: Http Post in C#
Requesting Gravatar...
1 suggestion

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

Long live to Haskell!!!
Left by josejuan on Jun 23, 2010 3:33 AM

# re: Http Post in C#
Requesting Gravatar...
Hey thank you very much! This is simple code fine works, good ideas
Left by Rimon Salmonik on Jul 08, 2010 12:00 AM

# re: Http Post in C#
Requesting Gravatar...
ok I can now send GET an POST http requests, but how to send PUT or DELETE http request?
Left by InTeGer on Jul 29, 2010 11:20 AM

# Dont download images
Requesting Gravatar...
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?
Left by selwonski on Jul 29, 2010 1:01 PM

# re: Http Post in C#
Requesting Gravatar...
You have no idea how much grief you saved me with this class. THANK YOU!!!!
Left by Truncated CoDr on Feb 24, 2011 12:09 PM

# re: Http Post in C#
Requesting Gravatar...
the code is Tooooooooooooooooooooooooo long just for a simple task
Left by nq on Mar 29, 2011 7:54 AM

# re: Http Post in C#
Requesting Gravatar...
thanks for the code, you saved me from having to write something similar
Left by Dave on Apr 24, 2011 4:01 PM

# re: Http Post in C#
Requesting Gravatar...
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
Left by Ranjeet Kuimar on Jun 20, 2011 1:11 AM

# re: Http Post in C#
Requesting Gravatar...
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?

Left by Ron Eskinder on Jul 07, 2011 4:50 PM

# I cannot seem to find a reference for System.Web
Requesting Gravatar...
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
Left by Gregg on Aug 08, 2011 9:27 AM

# Found reference
Requesting Gravatar...
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
Left by Gregg on Aug 08, 2011 10:44 AM

# re: Http Post in C#
Requesting Gravatar...
Your code worked great, Thanks for the help
Left by frankp on Aug 08, 2011 10:55 AM

# re: Http Post in C#
Requesting Gravatar...
With POST I get from sample code above 500er error from dice! Any ideas? with GET works fine, but what is wrong on POST?
Left by Volker on Oct 20, 2011 1:22 AM

# re: Http Post in C#
Requesting Gravatar...
Your code works really great.

I'm SOOOOOOOOOOOOO using it on every project.
Left by Gunbilegt on Feb 08, 2012 2:14 AM

# re: Http Post in C#
Requesting Gravatar...
Works fine but only at .NET v2 ? At v4 I can't System.Web in the list of .NET references.
Left by Antilles on Mar 08, 2012 10:26 AM

# re: Http Post in C#
Requesting Gravatar...
For C# generics refer
http://just-dotnet.blogspot.in/2012/06/c-generics-introduction.html
Left by Ramesh on Jul 15, 2012 2:16 PM

# re: Http Post in C#
Requesting Gravatar...
up for this thanks!
Left by JC on Dec 19, 2014 10:15 PM

Your comment:
 (will show your gravatar)


Copyright © Robert May | Powered by: GeeksWithBlogs.net | Join free