使用 System.Net.WebClient 发送 HTTP POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8222092/
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-09-03 16:03:02  来源:igfitidea点击:

Sending HTTP POST with System.Net.WebClient

.netvb.nethttpwebclient

提问by Endy Tjahjono

Is it possible to send HTTP POST with some form data with System.Net.WebClient?

是否可以使用 System.Net.WebClient 发送带有某些表单数据的 HTTP POST?

If not, is there another library like WebClient that can do HTTP POST? I know I can use System.Net.HttpWebRequest, but I'm looking for something that is not as verbose.

如果没有,是否有另一个像 WebClient 这样可以执行 HTTP POST 的库?我知道我可以使用 System.Net.HttpWebRequest,但我正在寻找不那么冗长的东西。

Hopefully it will look like this:

希望它看起来像这样:

Using client As New TheHTTPLib
    client.FormData("parm1") = "somevalue"
    result = client.DownloadString(someurl, Method.POST)
End Using

回答by Endy Tjahjono

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

根据@carlosfigueira 的回答,我进一步研究了 WebClient 的方法并找到了UploadValues,这正是我想要的:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

关键部分是这样的:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

它发送我输入的任何动词,它还帮助我创建一个正确的 url 编码表单数据,我只需要提供参数作为 namevaluecollection。

回答by carlosfigueira

WebClientdoesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

WebClient不直接支持表单数据,但您可以使用 UploadString 方法发送 HTTP 帖子:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

回答by faester

As far as the http verb is concerned the WebRequestmight be easier. You could go for something like:

就 http 动词而言,这WebRequest可能更容易。你可以去这样的事情:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream()and write it like a regular stream, but I hope it may be of some help.

显然,这缺少异常处理和编写请求正文(您可以r.GetRequestStream()像常规流一样使用和编写它,但我希望它可能有所帮助。