简体   繁体   中英

Bad Request [400] returned when REST API is called in C#

I was using Pushbots to send notifications to my android app and planning to write a method in C# to call the pushbots REST API to broad cast message to all connected phones. As Mentioned Here . But I'm getting a 400 response when request is made.

Here is my C# Class:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace RestAPICallTest
{
    class Program
    {
        static void Main(string[] args)
        {

            HttpWebRequest httpWReq =(HttpWebRequest)WebRequest.Create("https://api.pushbots.com/push/all");

            Encoding encoding = new UTF8Encoding();
            string postData = "{\"platform\":\"[1]\", \"msg\":\"Hi from Tali\" ,\"badge\":\"10\" ,\"sound\":\"default\"";
            byte[] data = encoding.GetBytes(postData);

            httpWReq.ProtocolVersion = HttpVersion.Version11;
            httpWReq.Method = "POST";
            httpWReq.ContentType = "application/json";//charset=UTF-8";
            httpWReq.Headers.Add("X-PUSHBOTS-APPID",
                                               "52ee4bd11d0ab1282a8b458e");
            httpWReq.Headers.Add("X-PUSHBOTS-SECRET",
                                            "b28825277373379b8c62126b16359d46");

            httpWReq.ContentLength = data.Length;


            Stream stream = httpWReq.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();

            HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
            string s = response.ToString();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            String jsonresponse = "";
            String temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                jsonresponse += temp;
            }
        }
    }
}

You are missing a closing curly bracket in your json body.

string postData = "{\\"platform\\":\\"[1]\\", \\"msg\\":\\"Hi from Tali\\" ,\\"badge\\":\\"10\\" ,\\"sound\\":\\"default\\" } ";

By the way the modern way to make HTTP requests from C# is HttpClient class. Your code will be much shorter and cleaner.

EDIT:

Ok, here is the HttpClient-style of your original code. It has async-only api so you should learn TPL. And that's another story.

using System;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;

namespace RestAPICallTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Run().Wait();
        }

        static async Task Run()
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("X-PUSHBOTS-APPID", "52ee4bd11d0ab1282a8b458e");
            httpClient.DefaultRequestHeaders.Add("X-PUSHBOTS-SECRET", "b28825277373379b8c62126b16359d46");

            var postData = "{\"platform\":\"[1]\", \"msg\":\"Hi from Tali\" ,\"badge\":\"10\" ,\"sound\":\"default\"}";
            var content = new StringContent(postData, Encoding.UTF8, "application/json");

            var response = await httpClient.PostAsync("https://api.pushbots.com/push/all", content);
            response.EnsureSuccessStatusCode();

            var responseJson = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseJson);
        }
    }
}

v.shashenko's answer is correct , but it will result another error "409 (conflict)" because of the quotation around platform array value.

//Incorrect
var postData = "{\"platform\":\"[1]\", \"msg\":\"Hi from Tali\" ,\"badge\":\"10\" ,\"sound\":\"default\"}";

//Correct
var postData = "{\"platform\":[1], \"msg\":\"Hi from Tali\" ,\"badge\":\"10\" ,\"sound\":\"default\"}";

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