简体   繁体   English

POST请求可以轻松替代HttpWebRequest吗?

[英]Easy alternative to HttpWebRequest for POST requests?

I need to trigger an action on a remote server using an http POST request. 我需要使用http POST请求在远程服务器上触发操作。 The server sends a response, either Y or N , to inform me if the action suceeded or not. 服务器发送一个响应,即YN ,以通知我该操作是否成功。

I am looking at using HttpWebRequest to do this, but this seems too complex. 我正在寻找使用HttpWebRequest做到这一点,但这似乎太复杂了。 To use this class you have to set all the headers, such as content type and content length. 要使用此类,您必须设置所有标头,例如内容类型和内容长度。

Is there a quicker way to send a POST request that doesn't require setting lower level properties such as this? 有没有一种更快的发送POST请求的方法,而该请求不需要设置诸如此类的较低级别的属性?

Try this WebClient 试试这个WebClient

 // Create a new WebClient instance.
 WebClient myWebClient = new WebClient();
 byte[] responseArray = myWebClient.UploadData("YOUR URI","POST","DATA to be Posted");

You can try with WebClient class. 您可以尝试使用WebClient类。 It's much more simpler and it's basically a wrapper for HttpWebRequest . 它要简单得多,并且基本上是HttpWebRequest包装器 It encapsulate all this complex logic you're trying to avoid. 它封装了您要避免的所有复杂逻辑。

I think the easiest built in class in the framework is WebClient . 我认为框架中最简单的内置类是WebClient Scott Hanselman has an example on how to perform gets and posts using it. 斯科特·汉塞尔曼(Scott Hanselman)有一个示例 ,说明如何使用它执行获取和发布。 This SO answer also has a good overview on how to post data. 这样的答案也很好地概述了如何发布数据。

If you have control over the server you're posting to, you might want to consider making it respond with HTTP status codes instead of some custom method. 如果您可以控制要发布到的服务器,则可能要考虑使其使用HTTP状态代码而不是某些自定义方法来响应。

the wcf web api project has an http client. wcf Web api项目具有一个http客户端。 It's super easy to use. 超级好用。 http://wcf.codeplex.com/ http://wcf.codeplex.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM