首页 > 解决方案 > 在 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);
                  });

将以下内容打印到控制台:

在此处输入图像描述

标签: c#apihttpclient

解决方案


推荐阅读