c# - 在 C# 中使用 HttpClient 使用原始 Json POST API
问题描述
我无法使以下 POST 请求正常工作。无论我尝试什么,它都会返回状态消息400 (Bad Request) 。
static HttpClient client = new HttpClient();
client.BaseAddress = new Uri("<<REDACTED>>");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// authorisation credentials go here, which work
var model = JsonConvert.SerializeObject(dialApi); //, Encoding.UTF8, "application/json"); //.DeserializeObject<Hello>(result);
var model1 = new StringContent(model, Encoding.UTF8, "application/json");
var x = "{\"data\":{\"Dest\":\"<<REDACTED>>\"}}";
//HttpResponseMessage response = await client.PostAsJsonAsync(path, model1);
HttpResponseMessage response = await client.PostAsJsonAsync(path, new StringContent(x, Encoding.UTF8, "application/json"));
问题可能是“内容”->“标题”->“内容类型”是“文本/html”(它应该是“应用程序/json”,但我似乎无法更改。默认标题已经设置到“应用程序/json”
我应该补充一点,我的 API 在 Postman 中工作,正文以“应用程序/json”的形式发送,带有原始设置:
我想知道是否有人可以提供帮助?
更新:
我已经尝试了在“重复”问题的答案中给出的替代实现,这也不起作用:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, path);
request.Content = new StringContent("{\"data\":{\"Dest\":\"<<>>redacted\"}}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
await client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
将以下内容打印到控制台:
解决方案
推荐阅读
- kubernetes - 安排一个 Kubernetes cronjob 只运行一次
- javascript - 如何处理 node.js 中的 json-parse 错误
- ios - largeTitleDisplayMode SwiftUI 中的字母间距
- java - 添加反应导航6.x后无法使用yarn android
- xamarin.forms - 具有最小限制的按钮计数
- r - 通过在 R 中使用列表的组计算平均值
- javascript - 如何在我的应用页面上从资源选择器呈现列表
- java - Gradle 项目显示版本不匹配且项目未构建
- reactjs - 我可以在不使用 Stripe Card Element 的情况下使用 Stipe api
- html - 跨域表单发布未按预期工作(未找到)