HTTP POST 通过 C#

5

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

通过C#可以进行HTTP POST吗?有人能提供一个例子吗?

4个回答

10

使用System.Net.WebClient非常简单:

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

此外还有:

  • UploadData - 二进制数据(byte[]
  • UploadFile - 来自文件的数据
  • UploadValues - 名称/值对数据(类似表单)

3

你可以使用 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();
}

1
你应该将使用try-catch块包裹起来,以便可以捕获400或500错误的数据。 - Spencer Ruport

0

我知道这是一个老问题,但是我为那些想要在最新的.NET(Core 5)中使用HttpClient(属于System.Net.Http命名空间)发送带有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://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0


0
这是一个很好的例子。你想在C#中使用WebRequest类,这将使它变得容易。在这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接