在 UWP 上以 Json 的形式发送请求

Send request as Json on UWP

我已经使用已部署的 Web 服务部署了 AzureML 发布的实验。我尝试使用 sample code provided in the configuration page, but universal apps do not implement Http.Formatting yet, thus I couldn't use postasjsonasync.

我尝试尽可能地遵循示例代码,但我得到的状态码是 415 "Unsupported Media Type",我在做什么错误?

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

非常感谢

您需要将对象序列化为 JSON 字符串(我建议使用 NewtonSoft.Json 以使其更容易)并相应地设置内容类型。这是我在我的 UWP 应用程序中使用的实现(请注意 _clientHttpClient):

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