2012-08-06 19 views
1

我想從互聯網上使用apache httpclient檢索文本文件。我使用下面的代碼:IllegalStateException java httpclient

 HttpClient httpclient = new DefaultHttpClient(); 
     HttpGet getHNMR = new HttpGet("http://www.hmdb.ca/labm/metabolites/" + HMDB + "/chemical/pred_hnmr_peaklist/" + HMDB + "_peaks.txt"); 
     HttpGet getCNMR = new HttpGet("http://www.hmdb.ca/labm/metabolites/" + HMDB + "/chemical/pred_cnmr_peaklist/" + HMDB + "_peaks.txt"); 

     try { 
      responseH = httpclient.execute(getHNMR); 
      responseC = httpclient.execute(getCNMR); 
     } catch (ClientProtocolException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      System.out.println("client exception"); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      System.out.println("ioexception"); 
     } 
     //Generate HNMR peak list 
     HttpEntity entityH = responseH.getEntity(); 
     HttpEntity entityC = responseH.getEntity();; 
     try { 
      HNMR = EntityUtils.toString(entityH); 
      CNMR = EntityUtils.toString(entityC); 
     } catch (ParseException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      System.out.println("parseexception"); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      System.out.println("ioexception"); 
     } 
    //Set peak lists to textarea 
     HC.setText(CNMR + "\n" + HNMR); 

我收到以下堆棧跟蹤:

Thread [pool-2-thread-1] (Suspended (exception IllegalStateException)) 
ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) line: 1128 
ThreadPoolExecutor$Worker.run() line: 603 
Thread.run() line: 679 

我不是那熟悉的調試,所以我不知道這正是發生。

+1

您是否試圖按順序下載文件?我不確定HttpClient實際上是否支持你的代碼中顯示的這種交織類型的操作。 – Dirk 2012-08-06 14:52:11

回答

2

響應正文必須消耗之前該連接可用於其他請求。您應該在下一次執行HTTP之前完全讀取響應InputStream。您的代碼應按以下順序出現:

responseH = httpclient.execute(getHNMR); 
    HttpEntity entityH = responseH.getEntity(); 
    HNMR = EntityUtils.toString(entityH); 

    responseC = httpclient.execute(getCNMR); 
    HttpEntity entityC = responseC.getEntity(); 
    CNMR = EntityUtils.toString(entityC); 
1

是否需要使用httpClient?鑑於它只是一個文本文件,你不需要任何帖子或獲取參數,更簡單的方法將是:

URL url = new URL("http://www.hmdb.ca/labm/metabolites/" + HMDB + "/chemical/pred_hnmr_peaklist/" + HMDB + "_peaks.txt"); 
InputStream response = url.openConnection().getInputStream();