Microsoft 认知 API 图像搜索

Microsoft Cognitive API Image Search

我正在尝试使用 Microsoft API of Bing 描述的图像 here

我只想通过在 post 请求正文中发送图像来使用图像洞察来查找相似图像,正如文档所说,我可以提供 url 或图像。

图像由 phone 相机拍摄并发送到 api,目的是最终获得相似的图像结果。

起初我收到一条错误消息,指出需要 'q' 参数,但我不想仅使用图片进行搜索查询。

所以我将 ContentType 更改为 "multipart/form-data" 并使用“/search?modulesRequested=similarimages”

这似乎做了一些事情,因为现在我没有收到任何错误,api 响应只是一个空字符串,所以我真的迷路了...

这是我发送请求的代码。

        public async Task<string> GetImageInsights(byte[] image)
    {
        var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages";

        var response = await RequestHelper.MakePostRequest(uri, new string(Encoding.UTF8.GetChars(image)), key, "multipart/form-data");

        var respString = await response.Content.ReadAsStringAsync();

        return respString;
    }
    public static async Task<HttpResponseMessage> MakePostRequest(string uri, string body, string key, string contentType)
    {
        var client = new HttpClient();

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

        // Request body
        byte[] byteData = Encoding.UTF8.GetBytes(body);

        using (var content = new ByteArrayContent(byteData))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            return await client.PostAsync(uri, content);
        }
    }

我在 Android

上使用 C# 和 Xamarin

为了使服务正常工作,表单部分需要名称和文件名:

public async Task<string> GetImageInsights(byte[] image)
{
    var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages";

    var response = await RequestHelper.MakePostRequest(uri, image, key);

    var respString = await response.Content.ReadAsStringAsync();

    return respString;
}

class RequestHelper
{ 
    public static async Task<HttpResponseMessage> MakePostRequest(String uri, byte[] imageData, string key)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);

            var content = new MultipartFormDataContent();
            content.Add(new ByteArrayContent(imageData), "image", "image.png");

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