1

我正在尝试使用 apache httpclient 从 Internet 检索文本文件。我正在使用以下代码:

        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  

我对调试不是很熟悉,所以我不确定到底发生了什么。

4

2 回答 2

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);
于 2012-08-06T14:56:21.750 回答
1

您是否需要使用 httpClient?鉴于它只是一个文本文件并且您不需要任何 post 或 get 参数,一个更简单的方法是:

URL url = new URL("http://www.hmdb.ca/labm/metabolites/" + HMDB + "/chemical/pred_hnmr_peaklist/" + HMDB + "_peaks.txt");
InputStream response = url.openConnection().getInputStream();
于 2012-08-06T15:16:48.000 回答