使用WebRequest方法以C#发送JSON POST-错误?

时间:2019-03-01 01:33:19

标签: c# json api httprequest

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

这是我收到的错误:

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

我没有将JSON传递给POST。我想念什么?

这是我的JSON字符串应如何组装的:这在邮递员中有效。

{
    "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; }
}

谢谢 挖

1 个答案:

答案 0 :(得分:0)

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

准备请求(主体是具有序列化内容的字符串变量):

    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):

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;
      }
    }
  }
}
相关问题