【发布时间】:2009-02-07 21:57:30
【问题描述】:
我想为在线游戏 (tribalwars.net) 编写一个自动机器人。我在学校学习 C#,但还没有涉及网络。
是否可以通过 C# 进行 HTTP POST?谁能举个例子?
【问题讨论】:
我想为在线游戏 (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();
}
【讨论】:
Here's 一个很好的例子。您想在 C# 中使用 WebRequest 类,这会很容易。
【讨论】:
我知道这是个老问题,但发布此问题是为了寻找快速示例,了解如何使用 HttpClient(System.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
【讨论】: