Google 自定义搜索 API - UWP

Google Custom Search API - UWP

我目前正在为学校做作业。任务是创建一个 UWP 应用程序,该应用程序使用 Google 自定义搜索 API 搜索 web,带有搜索栏和按钮单击,在网格视图或列表视图中显示结果。我一直在寻找有关该主题的教程,但那里没有太多内容。那里的内容与控制台应用程序有关。

我可以做一个简单的UI,明白XAML和后面的代码之间需要有数据绑定。我可以创建一个class。然而,尽管我尽了最大努力,但我无法使对 API 的调用正常工作并在列表视图上显示结果。我已经对一些值进行了硬编码,但下周将连接到实时数据。谁能提供任何帮助?

namespace Group_Project
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            String searchCode = textBox.Text;
            if (searchCode == null)
                throw new Exception("Need information in search");

            XDocument webRtn = new XDocument
                        (new XDeclaration("1.0", "utf-8", "yes"),
                         new XElement("SearchResults",
                             new XElement("SearchResult",
                                 new XAttribute("webiste", "www.google.com"),
                                 new XAttribute("search", "google"))));

            //String URL = "https://cse.google.com/cse?cx=009160378465265913901:plwe5st7ukl" + searchResults + ".xml";

            //Necessary to make the call to the internet to get the data.

            HttpClient client = new HttpClient();



            //var serviceresponse = client.GetAsync(URL).Result;

            //Checks for a success status code (200)

            //var serviceresponse = 200;

            //if (serviceresponse.IsSuccessStatusCode)

            //{

            //Get the content from the response

            //var responseContent = serviceresponse.Content;

            //Get the content into a string – async – you are still potentially pulling data down

            //string responseString = responseContent.ReadAsStringAsync().Result;

            //You don’t need to do this if you are testing with a local file but you will if connecting to the data

            //source directly

            //XDocument doc = XDocument.Parse(responseString);

            //Uncomment if you are reading from a local file

            XDocument doc = webRtn;

            //Using LINQ navigate to the data – this code will vary based on the incoming data structure and what data

            //you want to get

            // See detail on this below
            var query =
                   from element in doc.Element("SearchResults").Elements("SearchResult")
                   where element.Attribute("search").Value == "google"
                   select element.Attribute("webiste").Value;
            //Debug only

            Debug.WriteLine(query);

            ListView lst = new ListView();
            foreach (var website in query)
            {
                lst.Items.Add(website);
            }
            ListView Website = new ListView();
            WebsiteView.Items.Add("www.google.com");
            WebsiteView.Items.Add("www.bing.com");
            WebsiteView.Items.Add("www.msn.com");
            WebsiteView.Items.Add("www.fox.com");
            WebsiteView.Items.Add("www.abc.com");
            WebsiteView.Items.Add("www.nbc.com");

        }

    }
}

I can't make the call to the API work correctly.

首先,您可以参考这篇document to create your engine ID and get your API key. When you connect the api, you need to pass the two values to it. Then follow here完善您的api要求。然后您可以使用 HttpClient 请求获取 json 字符串的结果并将 json 字符串转换为您的视图模型。例如:

public MainPage()
{
    this.InitializeComponent();
    lists = new ObservableCollection<MyResultViewModel>();
}

public ObservableCollection<MyResultViewModel> lists { get; set; }
const string mykey = your_api_key;
const string engId = your_engine_ID;

private async void Button_Click(object sender, RoutedEventArgs e)
{
    string searchText = textBox.Text;
    HttpClient httpClient = new HttpClient();
    string baseUri = $"https://www.googleapis.com/customsearch/v1?key={mykey}&cx={engId}";
    Uri requestUri = new Uri(baseUri+"&q="+ searchText);

    HttpResponseMessage httpResponse = new HttpResponseMessage();
    string httpResponseBody = "";

    try
    {
        //Send the GET request
        httpResponse = await httpClient.GetAsync(requestUri);
        httpResponse.EnsureSuccessStatusCode();
        httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
        JsonObject obj = JsonValue.Parse(httpResponseBody).GetObject();
        JsonArray items = obj.GetNamedArray("items");
        for (uint i = 0; i < items.Count; i++)
        {
            string title = items.GetObjectAt(i).GetNamedString("title");
            MyResultViewModel vm = new MyResultViewModel() { Title = title };
            lists.Add(vm);
        }
    }
    catch (Exception ex)
    {
        httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
    }
}

Display the results on the listview.

.xaml:

<ListView ItemsSource="{x:Bind lists,Mode=OneWay}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:MyResultViewModel">
            <TextBlock Text="{x:Bind Title,Mode=OneWay}"></TextBlock>

        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

更新:

创建一个简单的视图模型来接收 json 数据。

public class MyResultViewModel 
{
    public string Title;
}