谷歌自定义搜索API-UWP
我目前正在为学校做作业。任务是创建一个UWP应用程序,该应用程序使用Google自定义搜索API搜索web,该API带有搜索栏和按钮单击,可在gridview或listview中显示搜索结果。我已经找了关于这个主题的教程,但是没有太多。这里的内容涉及控制台应用程序 我可以制作一个简单的UI,并且理解XAML和代码之间需要有数据绑定。我可以创建一个类。然而,尽管我尽了最大的努力,我还是无法使对API的调用正常工作并在listview上显示结果。我已经硬编码了一些值,但下周将连接到实时数据。有人能提供帮助吗谷歌自定义搜索API-UWP,uwp,google-custom-search,Uwp,Google Custom Search,我目前正在为学校做作业。任务是创建一个UWP应用程序,该应用程序使用Google自定义搜索API搜索web,该API带有搜索栏和按钮单击,可在gridview或listview中显示搜索结果。我已经找了关于这个主题的教程,但是没有太多。这里的内容涉及控制台应用程序 我可以制作一个简单的UI,并且理解XAML和代码之间需要有数据绑定。我可以创建一个类。然而,尽管我尽了最大的努力,我还是无法使对API的调用正常工作并在listview上显示结果。我已经硬编码了一些值,但下周将连接到实时数据。有人能提
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");
}
}
}
名称空间组\u项目
{
///
///可以单独使用或在框架内导航到的空页。
///
公共密封部分类主页面:第页
{
公共主页()
{
this.InitializeComponent();
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
字符串searchCode=textBox.Text;
if(searchCode==null)
抛出新异常(“搜索中需要信息”);
XDocument webRtn=新XDocument
(新的XDeclaration(“1.0”、“utf-8”、“是”),
新XElement(“搜索结果”,
新的XElement(“搜索结果”,
新XAttribute(“webiste”、“www.google.com”),
新的XAttribute(“搜索”、“谷歌”);
//字符串URL=”https://cse.google.com/cse?cx=009160378465265913901:plwe5st7ukl“+searchResults+”.xml”;
//需要打电话到互联网上获取数据。
HttpClient=新的HttpClient();
//var servicesponse=client.GetAsync(URL).Result;
//检查成功状态代码(200)
//var-servicesponse=200;
//if(serviceresponse.IsSuccessStatusCode)
//{
//从响应中获取内容
//var responseContent=servicesponse.Content;
//将内容转换为字符串–异步–您仍有可能向下拉取数据
//string responseString=responseContent.ReadAsStringAsync().Result;
//如果使用本地文件进行测试,则不需要执行此操作,但如果连接到数据,则需要执行此操作
//直接来源
//XDocument doc=XDocument.Parse(responseString);
//如果从本地文件读取,请取消注释
XDocument doc=webRtn;
//使用LINQ导航到数据–此代码将根据传入的数据结构和数据类型而有所不同
//你想得到什么
//详见下文
变量查询=
来自doc.element中的元素(“搜索结果”).Elements(“搜索结果”)
其中element.Attribute(“search”).Value==“google”
选择element.Attribute(“webiste”).Value;
//仅调试
Debug.WriteLine(查询);
ListView lst=新建ListView();
foreach(查询中的var网站)
{
1.项目添加(网站);
}
ListView网站=新建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的调用正常工作
首先,您可以参考此项来创建引擎ID并获取API密钥。连接API时,您需要将这两个值传递给它。然后,按照此项来完善您的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;
}
}
我的答案能解决你的问题吗?你还有其他问题吗?你会怎么做:MyResultViewModel我已经更新了我关于MyResultViewModel的答案。你可以根据实际需要进行补充。
<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>
public class MyResultViewModel
{
public string Title;
}