C# WebClient.UploadData 正确使用 post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1117421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:36:10  来源:igfitidea点击:

WebClient.UploadData correct usage for post request

c#webclient

提问by bumperbox

i think i am going a bit crazy, when i test this on my local webserver, it works fine when i go out to the live website, it returns a blank string instead of the data i am expecting

我想我有点疯狂,当我在本地网络服务器上测试它时,当我去实时网站时它工作正常,它返回一个空字符串而不是我期望的数据

i am not that familiar with C#, so i just wanted to check i am doing things right. the data is just plain ascii text

我对 C# 不太熟悉,所以我只是想检查一下我做的事情是否正确。数据只是普通的 ascii 文本

 wc = new WebClient();
 wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
 response = wc.UploadData(this.urlUpdate, Encoding.ASCII.GetBytes("data=" + HttpUtility.UrlEncode(buf.ToString())));

 s = Encoding.ASCII.GetString(response);

采纳答案by Marc Gravell

It really depends what you are trying to do... I'm not sure, for example, why you are url-encoding data in the body. An easier way to post key/value pairs is with UploadValues;

这真的取决于你想要做什么......例如,我不确定你为什么要在正文中对数据进行 url 编码。发布键/值对的更简单方法是使用UploadValues;

NameValueCollection inputs = new NameValueCollection();
string value = ...
inputs.Add("data", value);
webClient.UploadValues(address, inputs);