We help IT Professionals succeed at work.

How to do the HTTPS POST in c#?

power98888
power98888 asked
on
2,636 Views
Last Modified: 2013-12-16
Hi,
I try to do a https post to an url and pass some parameters. By doing in HTML form.  It is very simple to do a post and the page also redirect to the external page.
HTML CODE IS :
<form action="https://domainname/page/">
        <input type="hidden" name="param1" value="param1value" />        
        param2: <input type="text" name="param2" value="param2value" /><br />
        <input type="submit" name="submit" value="Submit" />
    </form>

In C# ASP, how to achieve post the value to the page and also re-direct to the page at the same time?
Comment
Watch Question

Author

Commented:
I forget to mention this is ASP.NET 2.0.
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
this answer is not for my question.  I update the HTML code then it looks like below.
How do I achive it in C#.NET for web app?
<form action="https://domainname/page/" method="post">
        <input type="hidden" name="param1" value="param1value" />        
        param2: <input type="text" name="param2" value="param2value" />
        <input type="submit" name="submit" value="Submit" />
    </form>


This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
RedKelvin,

I am sorry that I did not explain clearly.  I have the param1="param1value" and param2="param2value".
I do not want to build a form and user can click on the form to post.  I want C# web app to take those two values and then auto post to the url which is an external URL.  You know the original HTML Post will post the params and redirect to the page.  But when I use the post in C#, it only post the value there and no redirecting to the external url.  I can read the response but this is not what I want.

The example you post is only draw a post form and then it will does the HTML post.  This is not suitable for me.
Do you have any idea how to achieve the function?
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thank you very much for the replying.
Hi Codeclay,  what I confuse is the Response.Redirect after the Response string is received.
hI joechina, what do u mean Read from one and write to another one?
Please be aware the token have + sign then it won't work by passing via url.
Here is my code to post to
string strToken = "5fewfea+=jnf+wewiewfwe";
PostSubmitter post1 = new PostSubmitter();
        post1.Url = "https://pnpnet.support.qvalent.com/OnlinePaymentServlet";
        post1.PostItems.Add("param1", "value1");
        post1.PostItems.Add("param2", "value2");
        post1.PostItems.Add("refno", "555555");
        post1.PostItems.Add("token", strToken);
        post1.Type = PostSubmitter.PostTypeEnum.Post;
        string result1 = post1.Post();
       
       //this redirect does not work because it suppose to have some params at the back of the URL
      //or I can do it by post from a HTML form. The HTML post does the post and redirect at the same time
        Response.Redirect("https://pnpnet.support.qvalent.com/OnlinePaymentServlet");


The library of PostSubmitter is copy from this forum.

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

Open in new window

Author

Commented:
I have found the solution for the above question.  It works but I would like to see if Codeclay or joechina or others will suggest some other smart ways.

Thank you Codeclay or joechina.  Your posts give me ideas of resolving the solution.  I will close this post if no new ideas posted.
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks joechina,

What you says is correct. This is my solution.  Thank you for your reply.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.