未从Microsoft FaceAPI接收JSON数据

时间:2016-06-19 20:30:13

标签: c# wpf http wpf-controls microsoft-cognitive

我正在尝试使用Microsoft's FaceAPI从图片中获取JSON数据。我收到一个StatusCode确定,但没有得到任何重要的回报。我已经通过将其保存到文件来验证MemoryStream是否具有正确的数据(我从Image控件获取)。

    private async Task<string> GetJSON()
    {
        var client = new HttpClient();
        var queryString = HttpUtility.ParseQueryString(string.Empty);

        // Request headers
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "mykey");

        // Request parameters
        queryString["returnFaceId"] = "true";
        queryString["returnFaceLandmarks"] = "false";
        var uri = "https://api.projectoxford.ai/face/v1.0/detect?" + queryString;

        HttpResponseMessage response;

        // Request body
        byte[] byteData = ImageToByte();


        using (var content = new ByteArrayContent(byteData))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response = await client.PostAsync(uri, content);
        }

        return "";
    }

    private byte[] ImageToByte()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            videoBox.Dispatcher.Invoke(delegate
            {
                var encoder = new PngBitmapEncoder();

                var flippedBitmap = new TransformedBitmap();
                flippedBitmap.BeginInit();
                flippedBitmap.Source = (BitmapSource)videoBox.Source;
                var transform = new ScaleTransform(-1, 1);
                flippedBitmap.Transform = transform;
                flippedBitmap.EndInit();
                encoder.Frames.Add(BitmapFrame.Create(flippedBitmap));
                encoder.Save(stream);

            });

            using (FileStream test = new FileStream("snapshot.bmp", FileMode.Create))
            {
                stream.Position = 0;
                stream.CopyTo(test);
            }

            return stream.ToArray();
        }
    }

2 个答案:

答案 0 :(得分:1)

您想要致电await response.Content.ReadAsStringAsync()以获取JSON。

或者,您可以使用Microsoft.ProjectOxford.Face NuGet包为您做管道工作,并提供C#类型,从而减轻您解析JSON的繁琐。

答案 1 :(得分:0)

我不是ac #programmer,但在查看你的代码后,方法GetJSON返回硬编码的空字符串,这可能是你在调用此方法后没有从服务器返回任何内容的原因,或者第二个原因可能是你的异步服务器配置工作不正常,因此首先返回空白并稍后进行实际操作。