Post Method in Webclient

痴心易碎 提交于 2019-12-11 10:31:51

问题


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").


回答1:


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


来源:https://stackoverflow.com/questions/12528675/post-method-in-webclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!