【问题标题】:Reading from the same URL multiple times,not getting the data 2nd time多次从同一个 URL 读取,第二次没有得到数据
【发布时间】:2014-07-08 07:48:53
【问题描述】:

我有以下代码。一个连接,然后从该连接获取输入流并从输入流中读取。现在我想重用相同的连接再次获取输入流,但第二次我没有得到任何数据。

为什么会这样?我使用的不是同一个流,而是同一个连接。我们需要第二次重新打开连接吗?请解释一下。

URL url=new URL("https://www.google.co.in/");
HttpURLConnection httpURLConnection=(HttpURLConnection)
url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();

InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = in.readLine()) != null) 
System.out.println(inputLine);

System.out.println("**********************************");


/*Reading 2nd time*/
InputStream is=httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
String inputLines=null;
while ((inputLine = bf.readLine()) != null) 
System.out.println(inputLines);
bf.close();

【问题讨论】:

    标签: java http url inputstream httpurlconnection


    【解决方案1】:

    您没有获取数据,因为流中没有任何内容。要得到它,你必须发送另一个“GET”请求

    【讨论】:

    • “GET”请求是通过connect()方法还是openconnection()方法发送的?
    • 如果 connect 发出实际的“GET”请求,那么如果我们使用相同的 httpUrlCpnnection 实例再次连接,为什么在这种情况下我们没有得到结果?
    【解决方案2】:

    每个 HttpURLConnection 实例用于发出单个请求

    请参考javadoc

    http://download.java.net/jdk7/archive/b123/docs/api/java/net/HttpURLConnection.html

    【讨论】:

      【解决方案3】:

      第二次调用 getInputStream() 不会给你一个新的流,它只会给你一个你已经读过的流 - 那个流没有什么要读的了。

      如果你真的想看两遍,我建议你在第一次阅读时将其复制到String(如果内容不是文本,则复制到byte[])。然后,您可以从Stringbyte[] 读取它两次。

      如果内容特别大,另一种选择是将其复制到临时文件中。

      【讨论】:

      • 我想检查 HttpURLConnection 的实例实际指的是什么。在上面的代码中,如果在打印星号后。我再次调用 httpUrlConnection.connect ,那么我也没有得到输入流。为什么会这样?
      • Hirak 的回答解释了这一点。
      【解决方案4】:

      为什么要多次阅读?只需将值保存在变量中即可。

      List<String> inputLines =new ArrayList<String>();
      String inputLine;
      while ((inputLine = in.readLine()) != null) 
      inputLines.add(inputLine);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 2022-07-26
        • 2018-09-07
        • 1970-01-01
        • 2012-06-03
        • 1970-01-01
        相关资源
        最近更新 更多