【发布时间】:2019-09-06 18:55:57
【问题描述】:
在发布之前我已经检查了其他答案,所以请尽量不要在这里直接下结论。我正在使用 HttpClient 连接到我们使用的应用程序的 API,但它似乎无法识别或找到它所需的参数之一。 body 只是一个自定义对象。
这最初在 Postman 中不起作用,但是当我将 Content-Type 和 Body 更改为“x-www-form-urlencoded”时,我会收到 200 响应和所需的信息作为回报。查看here 我希望从 StringContent 切换到 FormUrlEncodedContent 会有所帮助,但我仍然得到相同的最终结果。
这是我的代码的精简版,希望有人能提供帮助。也许我错过了一步。
internal class API
{
private static HttpResponseMessage Response;
private static HttpClient Client;
private static FormUrlEncodedContent UrlEncodedContent;
private static Dictionary<string, string> bodyDictionary;
internal static async Task<string> Invoke(string command, string
name, object body = null, string method = "GET")
{
// Create HTTP Client
Client = new HttpClient();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string url = "https://" + name + "/Application/" + command;
switch(method)
{
case "POST":
bodyDictionary = Convert.ConvertClassToDictionary(body); // no problem here. fully tested
UrlEncodedContent = new FormUrlEncodedContent(bodyDictionary);
Post(url, UrlEncodedContent).Wait();
UrlEncodedContent.Dispose();
break;
}
return Response;
}
static private async Task Post(string url, FormUrlEncodedContent content)
{
Response = await Client.PostAsync(url, content);
}
}
它在 powershell 中运行良好并且非常简单,但这里不是一个选项。
$uri = "https://application.com/application/token"
$headers = @{"Accept"="application/json"; "Content-Type"="application/x-www-form-urlencoded"}
$body = @{"username"="user";"password"="pass";"grant_type"="password";"client_id"="id12345"}
$response = Invoke-RestMethod -Method Post -Uri $uri -Body $body -Headers $headers
【问题讨论】:
标签: c# dotnet-httpclient