C# 如何循环访问API Rest响应中的所有页面
我正在编写一个代码,可以从WooCommerce商店检索产品。API只返回100种产品,而总数量高达147种。API返回两个页面,但我似乎无法循环浏览这些页面 这是我目前的代码:C# 如何循环访问API Rest响应中的所有页面,c#,asp.net,json,api,woocommerce,C#,Asp.net,Json,Api,Woocommerce,我正在编写一个代码,可以从WooCommerce商店检索产品。API只返回100种产品,而总数量高达147种。API返回两个页面,但我似乎无法循环浏览这些页面 这是我目前的代码: protected void btnEnviar_Click(object sender, EventArgs e) { try { string apiUrl = "https://thestore.com/wp-json/wc/v3/prod
protected void btnEnviar_Click(object sender, EventArgs e)
{
try
{
string apiUrl = "https://thestore.com/wp-json/wc/v3/products?per_page=100";
string apiUsr = "usertoken";
string apiPwd = "passwordtoken";
string urlRequest1 = apiUrl;
HttpWebRequest requestWeb = (HttpWebRequest)WebRequest.Create(urlRequest1);
requestWeb.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
requestWeb.ContentType = "application/json";
requestWeb.Accept = "application/json";
requestWeb.Method = WebRequestMethods.Http.Get;
requestWeb.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr + ":" +apiPwd));
requestWeb.UseDefaultCredentials = true;
requestWeb.Proxy.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse responseHttpWeb = (HttpWebResponse)requestWeb.GetResponse();
Stream stream = responseHttpWeb.GetResponseStream();
//JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
using (StreamReader reader = new StreamReader(stream))
{
Stream webResponse = responseHttpWeb.GetResponseStream();
string lector = reader.ReadToEnd();
var mQuery = JsonConvert.DeserializeObject<List<Root>>(lector);
int contarObjetos = mQuery.Count();
contarItems.Text = contarObjetos.ToString();
if (contarObjetos == 0)
{
enviado.Text = "No existen registros";
}
else
{
foreach (var item in mQuery)
{
enviado.Text += item.id + ": " + item.name + " - " + item.status + "<br/><hr/>";
foreach(var elemento in item.categories)
{
enviado2.Text += elemento.id + ": " + elemento.name + "<br/><hr/>";
}
}
}
}
}
catch (Exception ex)
{
enviado.Text = ex.ToString();
}
}
但是我如何从api的头文件中获取页数并动态地将其分配到循环中呢
以下是我在《邮差》上看到的标题:
所以我想,如果我能访问那个标题,并将它分配给一个对象,并在每个循环中增加,我就会实现我想要的
我一直在浏览WooCommerce的API文档,但没有关于如何执行此操作的信息,并且在JSON的响应中没有返回页数的对象
对我来说,任何帮助都是巨大的 试试以下方法:
protected void btnEnviar_Click(object sender, EventArgs e)
{
try
{
string apiUrl = "https://thestore.com/wp-json/wc/v3/products?per_page=100";
string apiUsr = "usertoken";
string apiPwd = "passwordtoken";
int page = 1;
int totalPages = 0;
int count = 0;
do
{
string urlRequest = page == 1 ? apiUrl : apiUrl + $"&page={page}";
HttpWebRequest requestWeb = (HttpWebRequest)WebRequest.Create(urlRequest);
requestWeb.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
requestWeb.ContentType = "application/json";
requestWeb.Accept = "application/json";
requestWeb.Method = WebRequestMethods.Http.Get;
requestWeb.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr + ":" + apiPwd));
requestWeb.UseDefaultCredentials = true;
requestWeb.Proxy.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse responseHttpWeb = (HttpWebResponse)requestWeb.GetResponse();
string totalPages2 = responseHttpWeb.Headers["X-WP-TotalPages"];
// We don't really need to check for success. On failure it will write 0 and
// will break the cycle
int.TryParse(totalPages2, out totalPages);
using (var stream = responseHttpWeb.GetResponseStream())
using (var sr = new StreamReader(stream))
using (var jr = new JsonTextReader(sr))
{
var ser = new JsonSerializer();
var items = ser.Deserialize<List<Root>>(jr);
if (items.Count == 0)
{
if (page == 1)
{
enviado.Text = "No existen registros";
}
}
else
{
count += items.Count;
foreach (var item in items)
{
enviado.Text += item.id + ": " + item.name + " - " + item.status + "<br/><hr/>";
foreach (var elemento in item.categories)
{
enviado2.Text += elemento.id + ": " + elemento.name + "<br/><hr/>";
}
}
}
}
page++;
} while (page <= totalPages);
contarItems.Text = count.ToString();
}
catch (Exception ex)
{
enviado.Text = ex.ToString();
contarItems.Text = string.Empty;
}
}
protectedvoid btneviar\u单击(对象发送方,事件参数e)
{
尝试
{
字符串apiUrl=”https://thestore.com/wp-json/wc/v3/products?per_page=100";
字符串apiUsr=“usertoken”;
字符串apiPwd=“passwordtoken”;
int page=1;
int totalPages=0;
整数计数=0;
做
{
字符串URLRESQUEST=page==1?APIRL:APIRL+$“&page={page}”;
HttpWebRequest requestWeb=(HttpWebRequest)WebRequest.Create(urlRequest);
requestWeb.AutomaticDecompression=DecompressionMethods.GZip | DecompressionMethods.Deflate;
requestWeb.ContentType=“application/json”;
requestWeb.Accept=“application/json”;
requestWeb.Method=WebRequestMethods.Http.Get;
requestWeb.Headers[“Authorization”]=“Basic”+Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr+”:“+apiPwd));
requestWeb.UseDefaultCredentials=true;
requestWeb.Proxy.Credentials=CredentialCache.DefaultCredentials;
HttpWebResponse responseHttpWeb=(HttpWebResponse)requestWeb.GetResponse();
字符串totalPages2=responseHttpWeb.Headers[“X-WP-TotalPages”];
//我们真的不需要检查是否成功。失败时,它将写入0和
//将打破这个循环
int.TryParse(总页数2,总页数外);
使用(var stream=responseHttpWeb.GetResponseStream())
使用(var sr=新的StreamReader(stream))
使用(var jr=新的JsonTextReader(sr))
{
var ser=新的JsonSerializer();
var items=序列反序列化(jr);
如果(items.Count==0)
{
如果(第==1页)
{
enviado.Text=“不存在注册表”;
}
}
其他的
{
计数+=项目。计数;
foreach(项目中的var项目)
{
enviado.Text+=item.id+“:“+item.name+”-“+item.status+”
”;
foreach(项目类别中的变量elemento)
{
enviado2.Text+=elemento.id+“:“+elemento.name+”
”;
}
}
}
}
page++;
}while(page)您是否尝试过responseHttpWeb.Headers
?例如:string numPages=responseHttpWeb.Headers[“X-WP-TotalPages”];int numPages2;if(int.TryParse(numPages,out numPages2)){//Success!}
如果它提供了页数,我可以编写一些行代码来提取其他页面。是的!它返回了页数(本例中为2页)。谢谢。但是现在,我如何循环这些页面?
protected void btnEnviar_Click(object sender, EventArgs e)
{
try
{
string apiUrl = "https://thestore.com/wp-json/wc/v3/products?per_page=100";
string apiUsr = "usertoken";
string apiPwd = "passwordtoken";
int page = 1;
int totalPages = 0;
int count = 0;
do
{
string urlRequest = page == 1 ? apiUrl : apiUrl + $"&page={page}";
HttpWebRequest requestWeb = (HttpWebRequest)WebRequest.Create(urlRequest);
requestWeb.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
requestWeb.ContentType = "application/json";
requestWeb.Accept = "application/json";
requestWeb.Method = WebRequestMethods.Http.Get;
requestWeb.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr + ":" + apiPwd));
requestWeb.UseDefaultCredentials = true;
requestWeb.Proxy.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse responseHttpWeb = (HttpWebResponse)requestWeb.GetResponse();
string totalPages2 = responseHttpWeb.Headers["X-WP-TotalPages"];
// We don't really need to check for success. On failure it will write 0 and
// will break the cycle
int.TryParse(totalPages2, out totalPages);
using (var stream = responseHttpWeb.GetResponseStream())
using (var sr = new StreamReader(stream))
using (var jr = new JsonTextReader(sr))
{
var ser = new JsonSerializer();
var items = ser.Deserialize<List<Root>>(jr);
if (items.Count == 0)
{
if (page == 1)
{
enviado.Text = "No existen registros";
}
}
else
{
count += items.Count;
foreach (var item in items)
{
enviado.Text += item.id + ": " + item.name + " - " + item.status + "<br/><hr/>";
foreach (var elemento in item.categories)
{
enviado2.Text += elemento.id + ": " + elemento.name + "<br/><hr/>";
}
}
}
}
page++;
} while (page <= totalPages);
contarItems.Text = count.ToString();
}
catch (Exception ex)
{
enviado.Text = ex.ToString();
contarItems.Text = string.Empty;
}
}