2016-04-24 46 views
1

我正在用JSP網站來比較不同購物網站的產品價格,更有效的方式,我在下面的方式寫了1個jsp頁面代碼:有沒有寫這個Jsoup代碼

try 
{ 
jsoup.connect(first_website) 
/* code for fetching prices and images */ 
/* Html code for displaying prices and images */  
} catch(){} 

try 
{ 
jsoup.connect(second_website) 
/* code for fetching prices and images */ 
/* Html code for displaying prices and images */ 
} catch(){} 

try 
{ 
jsoup.connect(third_website) 
/* code for fetching prices and images */ 
/* Html code for displaying prices and images */ 
} catch(){} 

此代碼顯示單個搜索查詢在同一頁面上的三個網站的結果。但問題是,我的網站現在正在緩慢加載,並且某些時候一個或其他網站的結果不顯示。它給我以下錯誤:

org.jsoup.HttpStatusException: HTTP error fetching URL.Status=500,URL=/*websitename*/ 

回答

0

最好是使用多個線程來請求網站,所以你會發送請求到網站同時。

你能做到這一點會在java任務執行服務是這樣的:

FutureTask<Boolean> futureTask1 = new FutureTask<Boolean>(new Callable<Boolean>() 
    { 
     @Override 
     public Boolean call() throws Exception 
     { 
      try 
      { 
       //jsoup.connect(second_website) 
       /* code for fetching prices and images */ 
       /* Html code for displaying prices and images */ 
       return true; 
      } catch(Exception e){ 
       return false; 
      } 

     } 
    }); 

    FutureTask<Boolean> futureTask2 = new FutureTask<Boolean>(new Callable<Boolean>() 
    { 
     @Override 
     public Boolean call() throws Exception 
     { 
      //Same as above 
     } 
    }); 

    FutureTask<Boolean> futureTask3 = new FutureTask<Boolean>(new Callable<Boolean>() 
    { 
     @Override 
     public Boolean call() throws Exception 
     { 
      //Same as above 
     } 
    }); 

    ExecutorService executorService = Executors.newFixedThreadPool(3); 

    executorService.execute(futureTask1); 
    executorService.execute(futureTask2); 
    executorService.execute(futureTask3); 

    while (true){ 
     if(futureTask1.isDone() && futureTask2.isDone() && futureTask3.isDone()){ 
      //Here work is done 
      try 
      { 
       if(futureTask1.get()){ 
        //task 1 done it's work correctly 
       }else { 
        //some problem in task 
       } 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 

     } 

     try 
     { 
      Thread.sleep(100); 
     } 
     catch (InterruptedException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

如果你有這些任務之間的共同的邏輯,你可以創建一個實現Callable接口的類,並通過網站鏈接到它的構造。

相關問題