5

I want to code an auto bot for an online game (tribalwars.net). I'm learning C# in school, but haven't covered networking yet.

Is it possible to make HTTP POSTs though C#? Can anyone provide an example?

4

4 回答 4

10

Trivial with System.Net.WebClient:

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

There is also:

  • UploadData - binary (byte[])
  • UploadFile - from a file
  • UploadValues - name/value pairs (like a form)
于 2009-02-07T22:29:35.390 回答
3

You can use System.Net.HttpWebRequest:

Request

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();
}

Response

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using(StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    responseString = sr.ReadToEnd();
}
于 2009-02-07T22:05:22.583 回答
0

Here's a good example. You want to use the WebRequest class in C#, which will make this easy.

于 2009-02-07T22:04:00.963 回答
0

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

//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 类也有异步方法。有关课程的更多信息HttpClienthttps ://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0

于 2021-09-01T04:57:17.737 回答