【问题标题】:How to parse PostAsync response from Bing 2 API in C#?如何在 C# 中解析来自 Bing 2 API 的 PostAsync 响应?
【发布时间】:2017-05-12 21:19:28
【问题描述】:

Bing 几个月前发布了他们的 Search API 的新版本 (2)。 MS Cognitive Services 提供了使用其新搜索 API 2 的示例。
https://dev.cognitive.microsoft.com/docs/services/56b43f0ccf5ff8098cef3808/operations/571fab09dbe2d933e891028f

但是,工作示例带有 XML 响应,并且只有部分 C# 示例进行调用,但不解码结果。

有人可以解释或继续示例代码,以便将返回的对象解析为实际图像或图像 URL 吗?在下面的代码中,“content”变量的类型是 ByteArrayContent,但是从这个数组中获取信息需要什么? “response”变量的类型是HttpResponseMessage,但是如何从中提取图像或图像URL?

这将允许应用程序选择并显示一个或多个返回的图像。

非常感谢,蒂姆

这是 C# 代码示例:

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
        static void Main()
        {
            MakeRequest();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

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

            // Request parameters
            queryString["q"] = "cats";
            var uri = 
                "https://api.cognitive.microsoft.com/bing/v5.0/images/search?" 
                + queryString;

            HttpResponseMessage response;

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

            using (var content = new ByteArrayContent(byteData))
            {
               content.Headers.ContentType = new MediaTypeHeaderValue(
               "< your content type, i.e. application/json >");
               response = await client.PostAsync(uri, content);
            }

        }
    }
}   

【问题讨论】:

    标签: c# arrays parsing httpclient bing-api


    【解决方案1】:

    经过反复试验,我发现插入以下代码首先将搜索“响应”转换为字符串,然后转换为 JSON 对象,该对象可以解析为 Bing 的各种搜索结果。

    using Newtonsoft.Json;
    ....
    ....
    response = await client.PostAsync(uri, content);
    
    if (response.IsSuccessStatusCode)
    {
        Stringr str = await response.Content.ReadAsStringAsync();
    
        dynamic json = JsonConvert.DeserializeObject(str);
    }
    

    【讨论】:

      【解决方案2】:

      Here 是一个非常易于使用的必应搜索 API 客户端 API,您也可以从中获取网络搜索、图片、新闻……。下面是一个小例子,说明如何使用它在 C# 中从 Bing 搜索中获取图片。

          SearchResult result = await BingSearchHelper.Query("Bill Gates", new BingQueryParameters( apiKey: "APPKEY", count: 10, offset: 0, mkt: "en-us", safeSearch: "Moderate") );
      
      Console.WriteLine(result.images.value[0].thumbnailUrl);
      

      如果您仅将其用于此目的,则不需要 JSON 或 XML 转换。 希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-24
        • 1970-01-01
        相关资源
        最近更新 更多