您好我正在编写一个小任务来学习,查询stackoverflow api 我想在下面实现 ●该日期提出的问题数量 ●所有问题的总观看次数 ●在该日期的所有问题中使用的不同(即没有重复)逗号分隔的标签列表,按字母顺序排列。
我已经完成了api调用,但这不是我所期待的。首先,我没有找到api终点从stackexchange api获取日期问题。 任何建议都非常感谢
static void Main()
{
Console.WriteLine("Making stackoverflow API Call...");
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
{
client.BaseAddress = new Uri("https://api.stackexchange.com/docs");
// Int32 unixTimestamp = (Int32) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1,0,0,0,0))).TotalSeconds;
var unixStamp = Helper.ConvertToDateTime("2017, 09, 23, 0, 0, 0");
var response = client.GetAsync("questions?fromdate="+ unixStamp + "&todate="+ unixStamp + "&site=stackoverflow").Result;
response.EnsureSuccessStatusCode();
var s = response.Content.ReadAsStringAsync().Result;
var result = response.Content.ReadAsStringAsync().Result.Count();
Console.WriteLine("Total no.of questions asked: " + result);
}
Console.ReadLine();
}
答案 0 :(得分:1)
首先,您的基地址应为https://api.stackexchange.com/2.2
。
要获取在一天内创建的问题数量,您必须修改默认文件管理器以包含total
字段。
运行以下请求:
将返回:
{
"items": [],
"has_more": false,
"quota_max": 10000,
"quota_remaining": 9978,
"total": 3666
}
对于其他两个要求,您应该创建一个包含所需字段的新过滤器(如果您想使用返回的问题,可能需要在过滤器中包含更多字段以避免重复请求)。要创建,请参阅:filter/create和Custom Filters
获得结果后,您必须解析返回的JSON字符串(如果要返回XML,则必须解析XML)。您可以使用Newtonsoft或DataContractJsonSerializer中的内置版本(有关详细信息,请参阅here)。
以下是使用build in serializer的示例:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.IO;
[DataContract]
public class Question
{
// Question members...
}
[DataContract]
public class TotalQuestionsResult
{
[DataMember(Name = "items")]
public Question[] Items { get; set; }
[DataMember(Name = "has_more")]
public bool HasMore { get; set; }
[DataMember(Name = "quota_max")]
public int QuotaMax { get; set; }
[DataMember(Name = "quota_remaining")]
public int QuotaRemaining { get; set; }
[DataMember(Name = "total")]
public int Total { get; set; }
}
public async Task<int> GetTotalNumberOfQuestions()
{
// Get the data.
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
{
client.BaseAddress = new Uri("https://api.stackexchange.com/2.2");
var response = await client.GetAsync("questions?fromdate=1506211200&todate=1506297600&order=desc&sort=creation&site=stackoverflow&filter=!)5IW-5QudQH7_nJ7d.eBuocQb(B)");
var responseStream = new MemoryStream(await response.Content.ReadAsByteArrayAsync());
var serializer = new DataContractJsonSerializer(typeof(TotalQuestionsResult));
var result = (TotalQuestionsResult)serializer.ReadObject(responseStream);
return result.Total;
}
}