Salah Alshaal
Salah Alshaal

Reputation: 857

Send request as Json on UWP

I have deployed an AzureML published experiment with deployed web service. I tried to use the sample code provided in the configuration page, but universal apps do not implement Http.Formatting yet, thus I couldn't use postasjsonasync.

I tried to follow the sample code as much as possible, but I'm getting statuscode of 415 "Unsupported Media Type", What's the mistake I'm doing?

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
// client.BaseAddress = uri;

var scoreRequest = new
{
            Inputs = new Dictionary<string, StringTable>() {
                    {
                        "dataInput",
                        new StringTable()
                        {
                            ColumnNames = new [] {"Direction", "meanX", "meanY", "meanZ"},
                            Values = new [,] {  { "", x.ToString(), y.ToString(), z.ToString() },  }
                        }
                    },
                },
            GlobalParameters = new Dictionary<string, string>() { }
 };
 var stringContent = new StringContent(scoreRequest.ToString());
 HttpResponseMessage response = await client.PostAsync(uri, stringContent);

Many Thanks

Upvotes: 1

Views: 3253

Answers (1)

Bill
Bill

Reputation: 1479

You'll need to serialize the object to a JSON string (I recommend using NewtonSoft.Json to make it easier) and set the content type accordingly. Here's an implementation I'm using in my UWP apps (note that _client is an HttpClient):

    public async Task<HttpResponseMessage> PostAsJsonAsync<T>(Uri uri, T item)
    {
        var itemAsJson = JsonConvert.SerializeObject(item);
        var content = new StringContent(itemAsJson);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        return await _client.PostAsync(uri, content);
    }

Upvotes: 3

Related Questions