【问题标题】:HTTP POST Though C#HTTP POST 虽然 C#
【发布时间】:2009-02-07 21:57:30
【问题描述】:

我想为在线游戏 (tribalwars.net) 编写一个自动机器人。我在学校学习 C#,但还没有涉及网络。

是否可以通过 C# 进行 HTTP POST?谁能举个例子?

【问题讨论】:

    标签: c# .net http-post


    【解决方案1】:

    System.Net.WebClient 无关:

    using(WebClient client = new WebClient()) {
        string responseString = client.UploadString(address, requestString);
    }
    

    还有:

    • UploadData - 二进制 (byte[])
    • 上传文件 - 从文件
    • UploadValues - 名称/值对(如表单)

    【讨论】:

      【解决方案2】:

      你可以使用System.Net.HttpWebRequest:

      请求

      HttpWebRequest request= (HttpWebRequest)WebRequest.Create(url);
      request.ContentType="application/x-www-form-urlencoded";
      request.Method = "POST";
      request.KeepAlive = true;
      
      using (Stream requestStream = request.GetRequestStream())
      {
          requestStream.Write(BytePost,0,BytePost.Length);
          requestStream.Close();
      }
      

      回应

      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      using(StreamReader sr = new StreamReader(response.GetResponseStream()))
      {
          responseString = sr.ReadToEnd();
      }
      

      【讨论】:

      • 您应该将 using 封装在一个 try-catch 块中,以便您可以从 400 或 500 个错误中捕获数据。
      【解决方案3】:

      Here's 一个很好的例子。您想在 C# 中使用 WebRequest 类,这会很容易。

      【讨论】:

        【解决方案4】:

        我知道这是个老问题,但发布此问题是为了寻找快速示例,了解如何使用 HttpClientSystem.Net.Http 命名空间的一部分)在最新的 .NET(核心 5)中发送带有 json 正文的 Http Post 请求.示例:

        //Initialise httpClient, preferably static in some common or util class.
        public class Common
        {
            public static HttpClient HttpClient => new HttpClient
            {
                BaseAddress = new Uri("https://example.com")
            };
        }
        
        public class User
        {
            //Function, where you want to post data to api
            public void CreateUser(User user)
            {
                try
                {
                    //Set path to api
                    var apiUrl = "/api/users";
        
                    //Initialize Json body to be sent with request. Import namespaces Newtonsoft.Json and Newtonsoft.Json.Linq, to use JsonConvert and JObject.
                    var jObj = JObject.Parse(JsonConvert.SerializeObject(user));
                    var jsonBody = new StringContent(jObj.ToString(), Encoding.UTF8, "application/json");
        
                    //Initialize the http request message, and attach json body to it
                    var request = new HttpRequestMessage(HttpMethod.Post, apiUrl)
                    {
                        Content = jsonBody
                    };
        
                    // If you want to send headers like auth token, keys, etc then attach it to request header
                    var apiKey = "qwerty";
                    request.Headers.Add("api-key", apiKey);
        
                    //Get the response
                    using var response = Common.HttpClient.Send(request);
        
                    //EnsureSuccessStatusCode() checks if response is successful, else will throw an exception
                    response.EnsureSuccessStatusCode();
                }
                catch (System.Exception ex)
                {
                    //handle exception
                }
                
            }
        }
        

        为什么 HttpClient 是静态的或建议每个应用程序实例化一次:

        HttpClient 旨在被实例化一次并在整个过程中重复使用 应用程序的生命周期。实例化一个 HttpClient 类 每个请求都将耗尽大量可用的套接字数量 负载。这将导致 SocketException 错误。

        HttpClient 类也有异步方法。更多关于HttpClient类的信息:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-23
          • 2023-04-01
          • 2020-08-01
          • 2020-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多