【问题标题】:Send JSON POST in C# using WebRequest Method- Error?使用 WebRequest 方法在 C# 中发送 JSON POST - 错误?
【发布时间】:2019-03-01 01:33:19
【问题描述】:

我正在与 API 通信,我可以轻松执行 GET 命令!.... 我在让 POST 通过时遇到问题.......

这是我收到的错误:

"{\"error\":\"no data object in post\"}"

我没有将 JSON 传递给 POST。我错过了什么??

这是我的 JSON 字符串的组装方式:这在 Postman 中有效。

{
    "data": {
        "comments": "test comment",
        "lng": -96.7922,
        "lat": 46.87515
    }
}

这是我的代码:

WebRequest req = WebRequest.Create(@"https://the url.com/test?apiKey=testkey");
req.ContentType = "application/json";
req.Method = "POST";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));

using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
    var jsonstr = new Data
    {

        Comments = "hello world",
        Lng = -86.7922,
        Lat = 36.87515
    };

    string json = new JavaScriptSerializer().Serialize(jsonstr);

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

var httpResponse = (HttpWebResponse)req.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

这是数据类:

public partial class Data
{
    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("features")]
    public Feature[] Features { get; set; }

    [JsonProperty("lat")]
    public double Lat { get; set; }

    [JsonProperty("lng")]
    public double Lng { get; set; }

    [JsonProperty("comments")]
    public string Comments { get; set; }
}

谢谢 挖坟

【问题讨论】:

  • "no data object in post" -- 在进行 HTTP 调用之前,似乎没有任何数据被添加到请求 (req) 实例中......
  • 你应该做var jsonData = new { Data = jsonstr };string json = new JavaScriptSerializer().Serialize(jsonData );
  • 此错误信息由该网站生成,请咨询管理员。

标签: c# json api httprequest


【解决方案1】:

我认为这是因为您没有指定内容长度。它也(但不太可能)可能缺少 Accept 标头。这是我的任何 REST 客户端的代码片段:

准备请求(body 是一个带有序列化内容的字符串变量):

    HttpWebRequest Request = WebRequest.CreateHttp(BaseAddress.Uri);
    if (!string.IsNullOrWhiteSpace(method))
      Request.Method = method;
    else
      Request.Method = "GET";
    Request.Headers.Add("Authorization", BasicAuthInfo);
    Request.Accept = "application/json";
    if (!string.IsNullOrWhiteSpace(body))
    {
      UTF8Encoding encoding = new UTF8Encoding();
      byte[] byteBody = encoding.GetBytes(body);
      Request.ContentLength = byteBody.Length;
      using (Stream dataStream = Request.GetRequestStream())
        dataStream.Write(byteBody, 0, byteBody.Length);
      if (string.IsNullOrEmpty(Request.ContentType))
        Request.ContentType = "application/json";
    }

进行查询(其中 PrepareHttpWebRequest 是调用前一个 sn-p):

protected string JSONQuery(string subPath, string query = null, string method = null, NameValueCollection extraHeaders = null, string body = null)
{
  HttpWebRequest Request = PrepareHttpWebRequest(AuthenticationMethod.Basic, subPath, query, method, extraHeaders, body);
  using (WebResponse Response = Request.GetResponse())
  {
    using (Stream ResponseStream = Response.GetResponseStream())
    {
      using (StreamReader Reader = new StreamReader(ResponseStream, Encoding.UTF8))
      {
        string result = Reader.ReadToEnd();
        return result;
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多