【问题标题】:Using HTTP Post in C#在 C# 中使用 HTTP Post
【发布时间】:2017-11-27 03:51:20
【问题描述】:

我可以在 C# 中使用 HTTP Post 将数据包(不是文件)发送到远程服务器吗?如果是这样,该命令的外观如何?如果不是,发送此数据包的最佳方式是什么?此数据包由随机字符数据、2 字节标头、数据长度和要执行的操作组成,并构建在将其发送到服务器的解决方案中。我假设我会使用 GET 命令来获取服务器响应。

【问题讨论】:

标签: c# http


【解决方案1】:

您想在new System.Net.WebClient 上使用UploadData,它允许您发布任意数据(不一定是文件)

MSDN - WebClient.UploadData Method

【讨论】:

    【解决方案2】:

    这是一个通用方法。
    假设你有一个 [Data] 数据包要发送:

    HttpWebRequest httpRequest  = WebRequest.CreateHttp("Login Url");
    httpRequest.Method = WebRequestMethods.Http.Post;
    httpRequest.ContentType = "*The content type, if necessary*";
    httpRequest.ContentLength = [Data].Length;
    
    // Other Headers configuration if needed
    
    using (Stream _stream = httpRequest.GetRequestStream())
    {
       _stream.Write([Data], 0, [Data].Length);
    }
    
    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
    {
          // Get the response from the server
    }
    

    【讨论】:

    • 请将您的 cmets 从问题下方的 cmets 答案中移出。
    • @Mark Mucha 没问题
    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 2013-03-22
    • 2020-05-15
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多