对终点线服务器的递归HTTP请求不工作



我尝试在c#中使用递归进行2个请求

第一个请求工作正常,但第二个请求不工作

public class Finishline 
{
    static void Main(string[] args)
    {
        Finishline n = new Finishline();
        var a = n.lib_var("http://www.finishline.com/store/product?A=6961&categoryId=cat301644&productId=prod792423");
        Console.Write (a);
        Console.ReadLine();
    }
    public string lib_var (string url)
    {
        Console.Write (url);
        var request = WebRequest.CreateHttp(url);

        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        request.Headers["Accept-Language"] = "en-US,en;q=0.8";
        var response = request.GetResponse();
        Console.Write ("hu");
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var html = reader.ReadToEnd();
//Works upto here
            Console.Write (html);
//From thos it is not working
            lib_var ("http://www.finishline.com/store/catalog/ispu/ispuStoreLookup.jsp?latitude=34.0543797&longitude=-118.2672801&productId=prod792423&skuId=sku2622306");
            return html;
        }
    }
}

来自第二次呼叫

lib_var ("http://www.finishline.com/store/catalog/ispu/ispuStoreLookup.jsp?latitude=34.0543797&longitude=-118.2672801&productId=prod792423&skuId=sku2622306");

程序卡住了,如何使第二个呼叫工作??

你的代码在无限循环中结束,因为你的lib_var方法总是再次调用lib_var。所以调用堆栈是:lib_var -> lib_var -> lib_var -> lib_var -> ...并且永远不会回到Main

根据你想让程序做什么,这个问题有不同的解决方案:

  1. 你应该把第二个调用从lib_var方法移到Main

lib_var

 var html = reader.ReadToEnd();
//Works upto here
Console.Write (html);
//From thos it is not working
//lib_var ("http://www.finishline.com/store/catalog/ispu/ispuStoreLookup.jsp?latitude=34.0543797&longitude=-118.2672801&productId=prod792423&skuId=sku2622306");
return html;
主要

Finishline n = new Finishline();
var a = n.lib_var("http://www.finishline.com/store/product?A=6961&categoryId=cat301644&productId=prod792423");
Console.WriteLine(a);
var b = n.lib_var("http://www.finishline.com/store/catalog/ispu/ispuStoreLookup.jsp?latitude=34.0543797&longitude=-118.2672801&productId=prod792423&skuId=sku2622306");
Console.WriteLine(b);
Console.ReadLine();
  • 为lib_var添加第二个参数,指定是否应该进行递归调用。
  • lib_var

    public string lib_var (string url, bool doRecursive)
    {
        // ...
        if (doRecursive) 
        {
            lib_var ("http://www.finishline.com/store/catalog/ispu/ispuStoreLookup.jsp?latitude=34.0543797&longitude=-118.2672801&productId=prod792423&skuId=sku2622306", false);
        }
    }
    
    主要

    var a = n.lib_var("http://www.finishline.com/store/product?A=6961&categoryId=cat301644&productId=prod792423");
    Console.WriteLine(a);
    

    最新更新