java - IllegalStateException java httpclient

标签 java apache-httpclient-4.x illegalstateexception

我正在尝试使用 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  

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

最佳答案

必须在连接可用于另一个请求之前使用响应正文。您应该在下一次 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);

关于java - IllegalStateException java httpclient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11830090/

相关文章:

java - 如何使 US-ASCII 的 getBytes() 返回负数?

java - 如何在 Espresso 的 RecyclerView 中断言?

java - 匹配测试下方法内部创建的 HttpGet 对象

java - 使用 Java 重放 post 请求

java - 如何使用 apache httpclient fluent 4.3.2 在请求中设置字符集

尝试同时写入 websocket session 时,Tomcat 抛出 "The remote endpoint was in state [BINARY_FULL_WRITING] ..."

spring - 如何在 Spring Webflux 中使用 @RequestBody 并避免 IllegalStateException?

Java Spring MVC View 渲染并将 ArrayList<CustomModel> 通过表单提交绑定(bind)回 Controller

java - 英语语言计算器 [java]

android - 在磨损服务中调用 blockingConnect 时出现 IllegalStateException