0

I have a c# code that uses NameValueCollection, and then webclient to send a post request to API.

I need to use an equivalent request but using javascript instead of c#, I tried the following:

$.ajax({
            type: "POST",
            url:  "https://api.pushover.net/1/messages.json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: {
                "message": "xyz",
                "token": "xyz",
                "user": "xyz",
            },
            success: function(data) {
                console.log("push sent!");
            }
        });

But I get a 400 error, stating "bad request".

Please ignore the security perspective as the token & user are available to the user.

c# code is:

var parameters = new NameValueCollection {
            { "token", "xyz" },
            { "user", "xyz" },
            { "message", "xyz" }
        };

    using (var client = new WebClient())
    {
        client.UploadValues("https://api.pushover.net/1/messages.json", parameters);
    }
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
Hatem Husam
  • 177
  • 1
  • 3
  • 14

2 Answers2

0

I'm not at my machine right now so I can't test this, but I would guess that you're not setting the content type in the Header property of the webclient in c#, so that is defaulting to application/x-www-form-urlencoded but in javascript you're setting the content type to application/json. If the server is not set up to accept that type then you'll get a 400 error.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
0

It's probably because of the trailing comma in "user": "xyz",. A trailing comma is disallowed in json while perfect valid in .

I tested it using Postman (I can highly recommend, when working with APIs).

With a comma we get simple 400 - Bad request:

With a comma

Without a comma, we get at least an invalid token:

enter image description here

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111