• java.io.IOException: Attempted read from closed stream


    代码如下,执行的时候提示“java.io.IOException: Attempted read from closed stream.”
     @Test
        public void test_temp(){
            String url="http://ssov1.59iedu.com/login?TARGET=http://med.ihbedu.com:80/gateway/web/sso/auth&js&callback=loginThen&1470491151264&nocache=1470491171451";
            this.HttpGet(url);
    
        }
        public void HttpGet(String url) {
            CloseableHttpClient httpClient = HttpClients.createDefault();//建立httpclient
            HttpGet httpGet = new HttpGet(url);//建立httpget
            System.out.println("get请求的地址:" + httpGet.getURI());
            try {
                CloseableHttpResponse response = httpClient.execute(httpGet);//执行get请求,并结果保存
                System.out.println("get请求返回的状态码:" + response.getStatusLine().getStatusCode());
                HttpEntity httpEntity = response.getEntity();//将保存的response转为实体
                try {
    
                    if (httpEntity != null) {
                        {
                            System.out.println("get请求返回的response值:" + EntityUtils.toString(httpEntity));
                            System.out.println("lt的值:"+EntityUtils.toString(httpEntity).split("lt:"")[1].split("",")[0]);
                        }
                    }
                } finally {
                    EntityUtils.consume(httpEntity);//关闭实体
                    response.close();//关闭response
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();//关闭httpclient
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    原因是如下特别指出我的脚本中以下2个输出,这个输出中调用了2次 EntityUtils.toString(httpEntity) ,而根据httpclient的官方说明中,EntityUtils.toString(httpEntity) 这个被调用一次后就会自动销毁,而我调用了2次所有就报错了

    System.out.println("get请求返回的response值:" + EntityUtils.toString(httpEntity));
    System.out.println("lt的值:"+EntityUtils.toString(httpEntity).split("lt:"")[1].split("",")[0]);

    于是把这2个输出脚本改为如下即可,只要调用一次就好

    String responseStr=EntityUtils.toString(httpEntity);
    System.out.println("get请求返回的response值:" + responseStr);
    String str=responseStr.split("lt:"")[1].split("",")[0];
    System.out.println("lt的值:"+str);

     
  • 相关阅读:
    Revit API改变风管及管件尺寸
    Revit API注册事件
    Revit API创建标高,单位转换
    Revit API判断直线相交关系移动风管
    Revit MEP API找到连接器连接的连接器
    Revit MEP API连接器类别
    AngularJS如何编译和呈现页面
    AngularJS自定义Directive初体验
    Webpack基本用法
    对一个前端AngularJS,后端OData,ASP.NET Web API案例的理解
  • 原文地址:https://www.cnblogs.com/xxyBlogs/p/5745038.html
Copyright © 2020-2023  润新知