我想为一个在线游戏(tribalwars.net)编写自动机器人。我正在学校学习C#,但还没有学习网络编程。
通过C#可以进行HTTP POST吗?有人能提供一个例子吗?
使用System.Net.WebClient非常简单:
using(WebClient client = new WebClient()) {
string responseString = client.UploadString(address, requestString);
}
此外还有:
byte[]
)你可以使用 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();
}
我知道这是一个老问题,但是我为那些想要在最新的.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