提交带有标头和参数的POST
本文关键字:参数 POST 提交 | 更新日期: 2023-09-27 18:02:26
我需要连接到一个API,但他们给连接的所有例子都使用CURL。我需要在c#中实现它。我已经缩小到需要使用httpclient类,但我似乎找不到任何例子或教程来解释我到底需要什么。这是他们说要使用的CURL查询。谁能告诉我如何把它转换成c#的正确方向?
curl -X POST——header 'Content-Type: application/json'——header 'Accept: application/json'——header 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX' -d '{"grant_type":"密码","client_id":XXXXX,"用户名":"XXX.XXXXXX@XXXXXXXXX.com","密码":"XXXXXXXXXXXXX | XXXXXXXXXXXXX"} ' ' https://XXXXXXXXXXXX/XXXXXXXX/XXXXX/XXXXXX/authorize '
提前感谢:)
你可以像下面这样使用HttpClient类
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourdomain.com");
client.DefaultRequestHeaders.Accept.Clear();
//this line is optional in case you are using basic authentication
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "username", "password"))));
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "login")
});
HttpResponseMessage response = client.PostAsync("http//yourdomain.com", content).Result;
if (response.IsSuccessStatusCode)
{
var _result = response.Content.ContentToString();
}
}