简体   繁体   中英

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.......

This is the error I receive:

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

I'm not getting the JSON passed to the POST. What am I missing??

Here is how my JSON String should be assembled: This works in 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

I think that happens because you're not specifying content length. It also (but unlikely) can be Accept header missing. Here is a snipped from my code for any REST client:

Prepare request (body is a string variable with serialized content):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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