2

everyone。我正在编写一个使用Class HttpURLConnection连接到服务器的函数。在代码中,我建立了一个连接,按顺序调用getOutputStream()和getInputStream()方法。然后我断开连接。在此之后,我尝试获取通过getInputStream()方法获得的数据,但编译器会提醒NullPointerException。IOException:流被关闭,NullPointerException与HttpURLConnection断开连接

代码如下:

DataOutputStream out = null; 
    InputStreamReader inStrReader = null; 
    BufferedReader reader = null; 
    HttpURLConnection connection = null; 

    try { 
     URL postUrl = new URL(null, url, new sun.net.www.protocol.https.Handler()); 
     connection = (HttpURLConnection) postUrl.openConnection(); 
     ...//some setting methods 
     connection.connect(); 
     out = new DataOutputStream(connection.getOutputStream()); 
     out.writeBytes(JSONObject.toJSONString(param)); 
     out.flush(); 
     out.close(); 

     inStrReader = new InputStreamReader(connection.getInputStream(), "utf-8"); 
     reader = new BufferedReader(inStrReader); 
     connection.disconnect(); //<--HERE, release the connection 
     StringBuilder stringBuilder = new StringBuilder(); 
     for (String line = reader.readLine(); line != null; line = reader.readLine()) {  //<--null pointer 
      stringBuilder.append(line); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } finally { 
     if (out != null) { 
      try { 
       out.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     if (inStrReader != null) { 
      try { 
       inStrReader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

调试尝试后,当我移动断开线终于模块中的最后一行,一切都会好的。但是我很困惑,这发生在我已经将“输入流”的价值转嫁给“读者”时。

非常感谢。

回答

0

指定不等于读数,reader.readLine()开始从连接读取。

InputStreamReader使用连接读取的字节,断开之前,使用连接

InputStreamReader是字节流通向字符 流的桥梁读取的字节中:它读取字节,并...

+0

断开之前,我已经得到了InputStream对象为变量“读者”。但是,当我调试时,reader.readLine()方法获得nullpointexception。 – phinux

+0

但你没有看过任何东西,为了读取连接应该打开,因为你正在阅读使用它 – user7294900

0

请记住它是一个“流”。您需要有一个活动连接才能从流中读取数据。仅在您从流中检索到数据后才关闭连接。

+0

我明白了。谢谢你的明确解释。 – phinux

0

你正在做的所有事情都是错误的。这没有意义。

  1. 您正在断开连接,然后希望能够从连接中读取数据。这里总是废话。通常情况下,您不应该断开连接,因为您会干扰HTTP连接池。只要删除它,或者,如果您必须拥有它,请在完成所有关闭之后再进行操作。

  2. 您正在以错误的顺序关闭,但您根本不需要关闭inStrReader。关闭BufferedReader即可。请删除inStrReader.close()的所有代码。

  3. 您正在关闭out两次。不要这样做。

  4. connect()含蓄地发生。你不需要自己调用它。

  5. new URL(url)就足够了。你有没有需要提供HTTPS Handler距今约2003年

+0

Thx为您的建议。我只是因为惠普强化(HP企业安全产品)而维护这些代码。如果我删除finally模块中的close()方法,那么我将收到一些未释放资源的警告:stream。 – phinux

+0

然后不要将'InputStreamReader'声明为一个变量。只要做'新的BufferedReader(new InputStreamReader(connection.getInputStream(),“UTF-8”))'。 – EJP

+0

这是最初的代码,强化报告未发布的资源:流。然后我将InputStreamReader声明为一个变量。 – phinux

相关问题