我需要实现一个应用程序,将请求发布到给定的url并获得响应.

将请求发布到给定url并获得响应的最佳方法是什么?

请帮忙.

推荐答案

这个怎么样?

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main ()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
            // Set the Method property of the request to POST.
            request.Method = "POST";

            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes (postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream ();
            // Write the data to the request stream.
            dataStream.Write (byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close ();

            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}

它取自MSDN:MSDN on WebRequest

Asp.net相关问答推荐

在控制器中通过依赖项注入使用ASP.NET变量值时,不会持久化

使用 aspnet core SignalR 客户端为 VSIX 项目.

如何在 ASP.Net Core 中验证上传的文件

在 Web.Config 中模拟标签

如何在 MVC 中为国家和州/省创建 Select 列表

在 DataTextField 中组合两个字段.这可能吗?

System.Net.Http 版本冲突导致构建警告

在构建时自动停止/重新启动 ASP.NET 开发服务器

从 RowDataBound 事件的 gridview 从单元格中获取值

通过 jQuery 调用 ASP.NET 服务器端方法

System.Web.MVC 自 MS14-059 以来未复制到 bin 文件夹中.如何防止由于 Windows 更新而创建缺少 DLL 的构建?

ASP.Net 自定义客户端验证

错误:无法在 Web 服务器上开始调试... ASP.NET 4.0

使下拉列表项不可 Select

如何在 C# 中转换 TryCast?

跟踪点有什么用途?

如何在 C# 应用程序中调用 VBScript 文件?

发布网站项目时临时路径太长

如何防止aspxerrorpath作为查询字符串传递给 ASP.NET 自定义错误页面

.Net 上是否有 URL 验证器?