【问题标题】:Couldn't Post Data to api using post method无法使用 post 方法将数据发布到 api
【发布时间】:2020-06-28 04:23:26
【问题描述】:

我正在尝试使用以下请求将数据发布到 api,

{
    "authenticate": {
        "apikey": "API KEY"
    },
    "services": [
        {
            "call": "account/all",
            "identifier": {
                "offset": "0",
                "limit": "20"
            }
        }
    ]
}

但每次我都遇到错误

{"authenticate":{"apikey":null,"status":"failed","error":{"code":"E101","message":"JSON 错误:语法错误,格式错误的 JSON"}}}

我试过这个来发布请求

var request = (HttpWebRequest)WebRequest.Create(url);

            
            var data = Encoding.ASCII.GetBytes(query);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

【问题讨论】:

  • @viveknuna write() 方法需要 3 个参数而不是一个,所以我不能传递一个参数!

标签: c# json api http-post


【解决方案1】:

试试这个。

string json = "";
using (var client = new HttpClient())
{
    var response = await client.PostAsync(
        "url", 
         new StringContent(json, Encoding.UTF8, "application/json"));
}

【讨论】:

  • 尝试了您的代码,但响应内容返回 200 ok ,但在将内容作为流读取后出现同样的错误!
  • 使用这个来获取数据 await response.Content.ReadAsStringAsync();或没有异步 response.Content.ReadAsStringAsync().Result;
  • 是的,我正在使用 readasStringAsync,返回的数据是我问题中的错误。
  • 显示回复
  • 你在javascript的c#代码中获取json?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 2017-06-09
  • 2019-06-20
  • 2022-01-15
  • 2023-02-16
  • 2020-09-10
相关资源
最近更新 更多