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 Answers 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)
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();
}
1
  • 1
    You should encase the using in a try-catch block so that you can capture data from 400 or 500 errors. Commented Feb 7, 2009 at 22:22
0

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

0

I understand this is old question, but posting this for someone looking for quick example on how to send Http Post request with json body in latest .NET (Core 5), using HttpClient (part of System.Net.Http namespace). Example:

//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
        }
        
    }
}

Why is HttpClient static or recommended to be instantiated once per application:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

HttpClient class has async methods too. More info on HttpClient class: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.