简体   繁体   English

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

[英]Send JSON POST in C# using WebRequest Method- Error?

I'm communicating with an API and I can perform a GET command with ease!.... I am having issues getting the POST to go through....... 我正在与API通信,可以轻松执行GET命令!....我在使POST通过时遇到了问题。

This is the error I receive: 这是我收到的错误:

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

I'm not getting the JSON passed to the POST. 我没有将JSON传递给POST。 What am I missing?? 我想念什么?

Here is how my JSON String should be assembled: This works in Postman. 这是我的JSON字符串应如何组装的:在Postman中有效。

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

Here is my code: 这是我的代码:

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();
}

Here is the Data Class: 这是数据类:

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

Thanks tdigges 谢谢tdigges

I think that happens because you're not specifying content length. 我认为是因为您没有指定内容长度。 It also (but unlikely) can be Accept header missing. 它还(但不太可能)可能是缺少Accept标头。 Here is a snipped from my code for any REST client: 这是我的任何REST客户端代码的摘录:

Prepare request (body is a string variable with serialized content): 准备请求(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";
    }

Make a query (where PrepareHttpWebRequest is call to previous snippet): 进行查询(对上一个代码段调用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;
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM