【问题标题】:HttpClient Post request not sending post parameters in C#HttpClient Post请求未在C#中发送post参数
【发布时间】:2021-07-27 22:31:33
【问题描述】:

我正在控制台应用程序中发送发布请求,但似乎无法发送发布参数。 这是我的代码

{
    string pass_url = "https://staging.fooddesk.be/api/v1/add_new_partner_pws";
    string postString = "[{\n\"product_name\": \"kip absrert\",\n\"producer_name\": \"Imperial Meat Products\",\n\"producer_art_num\": \"123\",\n\"supplier_name\": \"Vagro\",\n\"supplier_art_num\": \"12345\",\n\"ean_code\": \"5411153011327\",\n\"partner_art_nbr\": \"12345\"\n}]\"";
    var multipartContent = new MultipartFormDataContent();
    multipartContent.Add(new StringContent("pws_data" ) , postString) ;
    Uri requestUri = new Uri(pass_url);
    using (var objClint = new System.Net.Http.HttpClient())
    {
        objClint.DefaultRequestHeaders.Add("X-API-KEY", "ABCD");
        objClint.DefaultRequestHeaders.Add("X-COMP-KEY", "XYZ");
        System.Net.Http.HttpResponseMessage response = objClint.PostAsync(requestUri, multipartContent).Result;
        Console.WriteLine(response);
        if (response.IsSuccessStatusCode)
        {
            string json = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(json);
        }
    }
}

我在第 4 行遇到异常。 请让我知道我应该如何在 http 客户端发布请求中发送发布数据。 提前致谢。

【问题讨论】:

  • 当您收到“异常”时,发布确切的消息非常有帮助 - 通常包含有用的信息
  • ... 和往常一样:you are using HttpClient wrong

标签: c# .net winforms api httpclient


【解决方案1】:

我相信你在第 4 行混淆了你的论点。

查看the docs的用法。

试试

multipartContent.Add(new StringContent(postString) , "pws_data") ;

另外,post 字符串在 ] 之后的末尾有一个额外的引号。删除它应该会有所帮助。

[{ "product_name": "kip absrert", "producer_name": "帝国肉制品", "producer_art_num": "123", "supplier_name": "Vagro", "supplier_art_num": "12345", "ean_code": "5411153011327", “partner_art_nbr”:“12345” }]"

【讨论】:

  • 您好,谢谢,我更新了该行并且异常消失了。但是api的另一面仍然没有得到posted参数。有什么线索吗?
  • 我收到 403 禁止响应。可能 API KEY 或 COMP KEY 不正确。
  • 我现在收到 400 错误请求响应。我会用你的 API Key 和 Comp Key 删除你上面的评论。
  • 是的,它返回 400,因为 pws_data 对另一方不可用。
  • string postString = "[{\n\"product_name\": \"kip absrert\",\n\"producer_name\": \"Imperial Meat Products\",\n\"producer_art_num \": \"123\",\n\"supplier_name\": \"Vagro\",\n\"supplier_art_num\": \"12345\",\n\"ean_code\": \"5411153011327\" ,\n\"partner_art_nbr\": \"12345\"\n}]\""; 最后,在 ']' 字符之后,删除 \"。它在请求中添加了一个额外的双引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2013-09-03
  • 2016-01-25
相关资源
最近更新 更多