TCP connection is not reused for HTTP requests with HttpURLConnection

后端 未结 2 482
刺人心
刺人心 2020-12-17 03:16

I\'m have created an application which sends GET requests to a URL, and then downloads the full content of that page.

The client sends a GET to e.g. stackoverflow.c

2条回答
  •  渐次进展
    2020-12-17 03:30

    Found the problem! I was not reading the input stream properly. This caused the input stream objects to hang, and they could not be reused.

    I only defined it, like this:

    InputStreamReader isr = new InputStreamReader(connection.getInputStream());
    

    but I never read from it :-)

    I changed the read method as well. Instead of a buffered reader I stole this:

    InputStream in = null; 
    String queryResult = "";
    try {
         URL url = new URL(archiveQuery);
         HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
         HttpURLConnection httpConn = (HttpURLConnection) urlConn;
         httpConn.setAllowUserInteraction(false);
         httpConn.connect();
         in = httpConn.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(in);
         ByteArrayBuffer baf = new ByteArrayBuffer(50);
         int read = 0;
         int bufSize = 512;
         byte[] buffer = new byte[bufSize];
         while(true){
             read = bis.read(buffer);
             if(read==-1){
               break;
             }
             baf.append(buffer, 0, read);
         }
         queryResult = new String(baf.toByteArray());
         } catch (MalformedURLException e) {
              // DEBUG
              Log.e("DEBUG: ", e.toString());
         } catch (IOException e) {
              // DEBUG
              Log.e("DEBUG: ", e.toString());
         } 
    }
    

    From here: Reading HttpURLConnection InputStream - manual buffer or BufferedInputStream?

提交回复
热议问题