我目前正在为学校做作业。任务是创建一个UWP应用,该应用使用带有搜索栏和按钮单击的Google自定义搜索API来在Web上搜索,并在gridview或listview中显示结果。我一直在寻找有关该主题的教程,但是这里没有太多内容。那里处理的是控制台应用程序。
我可以制作一个简单的UI,并了解XAML与后面的代码之间需要数据绑定。我可以创建一个类。但是,尽管我已尽力而为,但我仍无法正确调用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");
}
}
}
我无法正确调用API。
首先,您可以参考此document创建引擎ID并获取API密钥。连接api时,需要将两个值传递给它。然后按照here完善您的api请求。然后,您可以使用HttpClient请求获取json字符串的结果,并将json字符串转换为您的viewmodel。例如:
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;
}
}
在列表视图上显示结果。
。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;
}