Shahid Karimi
Shahid Karimi

Reputation: 4357

C# posting data to webserver using POST method issue

While posting data I am getting issue. The issue is in the & character. I am posting a string which may contain anything. like "this&this, how are you?". But in the above case only "this" is sending. String from the character & is stripped.

Code I tried:

  var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://mywebsite.com/import.php");
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write("tname=sanam&temail=sanam@" + Guid.NewGuid().ToString("N") + ".com&tbody=" + this.body + "&ttitle=" + this.title);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    retStr = streamReader.ReadToEnd();
                }
                //retStr = "POST: " + this.body;

            }

Does anybody know how to send anything to the server using C#? Thanks in advance.

Upvotes: 0

Views: 243

Answers (1)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

Encode the free text fields trough

System.Web.HttpUtility.UrlEncode()

IE:

streamWriter.Write("tname=sanam&temail=sanam@" + Guid.NewGuid().ToString("N") + ".com&tbody=" + HttpUtility.UrlEncode(this.body) + "&ttitle=" + HttpUtility.UrlEncode(this.title));

Upvotes: 3

Related Questions