如何在 C# 中使用 WebClient 将数据发布到特定 URL
我需要将“HTTP Post”与 WebClient 结合使用,将一些数据发布到我拥有的特定 URL。
现在,我知道这可以通过 WebRequest 来完成,但由于某些原因我想改用 WebClient。这可能吗?如果是这样,有人可以向我展示一些例子或指出我正确的方向吗?
I need to use "HTTP Post" with WebClient to post some data to a specific URL I have.
Now, I know this can be accomplished with WebRequest but for some reasons I want to use WebClient instead. Is that possible? If so, can someone show me some example or point me to the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我刚刚找到了解决方案,是的,它比我想象的要容易:)
所以这就是解决方案:
它就像魅力一样:)
I just found the solution and yea it was easier than I thought :)
so here is the solution:
it works like charm :)
有一个名为 UploadValues 的内置方法,可以发送 HTTP POST(或任何类型的 HTTP 方法) ) AND 以正确的数据格式处理请求正文的构造(用“&”连接参数并通过 url 编码转义字符):
There is a built in method called UploadValues that can send HTTP POST (or any kind of HTTP methods) AND handles the construction of request body (concatenating parameters with "&" and escaping characters by url encoding) in proper form data format:
使用
WebClient.UploadString
或WebClient.UploadData
您可以轻松地将数据 POST 到服务器。我将展示一个使用 UploadData 的示例,因为 UploadString 的使用方式与 DownloadString 相同。更多:http://www.daveamenta.com/2008-05/c -webclient-用法/
Using
WebClient.UploadString
orWebClient.UploadData
you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.More: http://www.daveamenta.com/2008-05/c-webclient-usage/
使用简单的
client.UploadString(adress, content);
通常工作得很好,但我认为应该记住,如果没有返回 HTTP 成功状态代码,将会抛出WebException
。我通常这样处理它以打印远程服务器返回的任何异常消息:Using simple
client.UploadString(adress, content);
normally works fine but I think it should be remembered that aWebException
will be thrown if not a HTTP successful status code is returned. I usually handle it like this to print any exception message the remote server is returning:使用 webapiclient 与模型发送序列化 json 参数请求。
PostModel.cs
WebApiClient.cs
业务调用者方法
Using webapiclient with model send serialize json parameter request.
PostModel.cs
WebApiClient.cs
Business caller method
大多数答案都是旧的。只是想分享对我有用的东西。为了异步执行操作,即在 .NET 6.0 Preview 7、.NET Core 和其他版本中使用 WebClient 异步将数据发布到特定 URL,可以使用 WebClient.UploadStringTaskAsync 方法。
使用命名空间
System.Net;
,并且对于类ResponseType
来捕获来自服务器的响应,我们可以使用此方法将POST
数据发送到具体网址。确保在调用此方法时使用await
关键字Most of the answers are old. Just wanted to share what worked for me. In the interest of doing things asynchronously i.e. to post data to specific URL using WebClient asynchronously in .NET 6.0 Preview 7, .NET Core and other versions can be done using WebClient.UploadStringTaskAsync Method.
Use namespace
System.Net;
and for a classResponseType
to capture the response from the server, we can use this method toPOST
data to a specific URL. Make sure to use theawait
keyword while calling this method这是明确的答案:
Here is the crisp answer: