【发布时间】:2020-01-27 15:32:54
【问题描述】:
我在使用 HttpClient 时尝试发送 POST 请求。当我运行代码时,我得到了未经授权的响应。但我可以让它在 PostMan 中工作。下面是我当前的代码 sn-p 和我正在尝试执行的图片。我想补充一下,我正在尝试在我的身体中发送一个 json 字符串。
using (HttpClient client = new HttpClient())
{
var connectionUrl = "https://api.accusoft.com/prizmdoc/ViewingSession";
var content = new Dictionary<string, string> { { "type", "upload" }, { "displayName", "testdoc" } };
// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(content);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
//client.DefaultRequestHeaders.Add("Acs-Api-Key", "aPsmKCmvkZHf9VakCmfHB8COmzRxXY5FDhj8F1FU1IGmQlOkfjiKESKxfm38lhey");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Acs-Api-Key", "aPsmKCmvkZHf9VakCmfHB8COmzRxXY5FDhj8F1FU1IGmQlOkfjiKESKxfm38lhey");
// Do the actual request and await the response
var httpResponse = httpClient.PostAsync(connectionUrl, httpContent).Result;
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
// Do something with response. Example get content:
var connectionContent = httpResponse.Content.ReadAsStringAsync().Result;
}
else
{
// Handle a bad response
return;
}
}
}
【问题讨论】:
-
使用像 wireshark 或 fiddler 这样的嗅探器,比较 Postman 结果和 c# 结果之间的第一个请求标头。一个或多个标题不同。然后让 c# 应用程序头看起来和邮递员头完全一样。
-
会不会是因为你的 api-key 的值太短了?即它很快就会过期
-
不,api密钥不是随机生成的。它用于所有 api 调用
标签: c# httpwebrequest httpclient