然而,有效的示例是XML响应,并且只有部分C#示例进行调用,但不解码结果。
有人可以解释或继续示例代码,以便将返回的对象解析为实际图像或图像URL吗?在下面的代码中,"内容"变量是ByteArrayContent类型,但是从这个数组中获取信息需要什么? "响应"变量的类型为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);
}
}
}
}
答案 0 :(得分:1)
经过一番试验&amp;错误,我发现插入以下代码首先将搜索“response”转换为字符串,然后转换为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);
}
答案 1 :(得分:0)
Here是一款非常易于使用的bing搜索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转换。 我希望它会对你有所帮助。