【问题标题】:Post Method in WebclientWebclient 中的 Post 方法
【发布时间】:2012-09-21 10:21:03
【问题描述】:

网络服务发布方法对我来说是新的。你能帮我看看我做错了什么吗?

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

顺便说一句,如果我访问带有参数和值的 url,它的工作正常

喜欢这个("http://localhost:60696/service/getlogin/username,123,password,456").

【问题讨论】:

    标签: windows-phone-7 c#-4.0 silverlight-4.0 webclient webclient.uploaddata


    【解决方案1】:

    postdata 似乎编码错误,应该是这样的:

    postData.AppendFormat("{0}={1}", "username", HttpUtility.UrlEncode(textBox1.Text));
    postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(textBox2.Text));
    

    【讨论】:

    • 如果您需要我的建议,请使用 RestSharp 而不是手动提出请求,这将为您节省大量时间和头痛!!!
    • Restsharp?...我以前没用过。你能把它是什么以及如何使用它的参考资料发给我吗
    • 对于其他可能有同样问题但解决方案不起作用的人:检查服务器上的重定向规则。我的请求发送到domain.com,服务器向我发送了“301 永久移动”=> WebRequest 将再次发送,但它似乎作为 GET 请求发送,因此您的所有 Post 数据都丢失了!
    猜你喜欢
    • 2014-04-04
    • 2020-09-16
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多