1

web service post method is new for me. can u pls help me out what am i doing wrong.

WebClient webClient = new WebClient();

webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                webClient.Encoding = Encoding.UTF8;
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler((sender, e) =>
                {
                    if (e.Error != null)
                    {
                        return;
                    }
                    string result = e.Result;
                });
                string uri = "http://localhost:60696/service/getlogin/";
                StringBuilder postData = new StringBuilder();
                postData.AppendFormat("/{0}/{1}", "username", HttpUtility.UrlEncode(textBox1.Text));
                postData.AppendFormat("/{0}/{1}", "password", HttpUtility.UrlEncode(textBox2.Text));
                webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
                webClient.UploadStringAsync(new Uri(uri, UriKind.RelativeOrAbsolute),"POST", postData.ToString());

by the way, If i access the url with the parameters and value appended its working fine

like this ("http://localhost:60696/service/getlogin/username,123,password,456").

John Conde
  • 217,595
  • 99
  • 455
  • 496
BharathNadadur
  • 557
  • 1
  • 6
  • 13

1 Answers1

2

The postdata seems wrongly encoded, should be something like this:

postData.AppendFormat("{0}={1}", "username", HttpUtility.UrlEncode(textBox1.Text));
postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(textBox2.Text));
Pedro Lamas
  • 7,185
  • 4
  • 27
  • 35
  • If you want my advice, just use RestSharp instead of making the requests by hand, it will save you a lot of time and headaches!!! – Pedro Lamas Sep 24 '12 at 10:05
  • Restsharp?... I have not used it before. Can u send me the references of what it is and how to use it – BharathNadadur Sep 24 '12 at 12:08
  • For others who may have the same problem but the solution doesn't work: Check the redirection rules on the server. My request went to http://domain.com and the server sent me a "301 Moved permanently" => The WebRequest will then be sent again but it seems to be sent as a GET Request so all your Post data gets lost!! – landi Jul 25 '13 at 20:15