0

I'm trying to send some data using the example in the page of onesignal

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic xxx");

var obj = new
{
    app_id = "xxx",
    contents = new { en = "English Message" },
    included_segments = new string[] { "Active Users" }
};
var param = JsonConvert.SerializeObject(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

This coded works fine, but I'm using Flurl to make a request to onesignal like this:

var body = new
{
    app_id = "xxx",
    contents = new
    {
        es = "Mensaje prueba"

    },
    included_segments = new string[] { "All" }
};
string param = JsonConvert.SerializeObject(body);
var content = new System.Net.Http.ByteArrayContent(Encoding.UTF8.GetBytes(param));

var response = await new Flurl.Url(urlbase)
    .AppendPathSegment("notifications")
    .WithHeader("Content-Type", "application/json; charset=utf-8")
    .WithHeader("Authorization", "Basic xxx")
    .PostAsync(content)
    .ReceiveString();

but I'm getting the "Bad request". Please someone could help to point how to make the same call with Flurl?

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • 1
    Just use `PostJsonAsync(body)` instead of `PostAsync`, do not serialize a body itself. Let Flurl do it its way. – Karel Kral Mar 07 '19 at 20:13

1 Answers1

1

As mentioned in the first comment, you're doing more work than you need to. Flurl will serialize body for you, so remove these lines:

string param = JsonConvert.SerializeObject(body);
var content = new System.Net.Http.ByteArrayContent(Encoding.UTF8.GetBytes(param));

And post body directly using PostJsonAsync:

var response = await urlbase
    ...
    .PostJsonAsync(body)
    .ReceiveString();
Todd Menier
  • 37,557
  • 17
  • 150
  • 173