I understand with sockets in Java and for one with the HTTP protocol. I send a request to the site in order to get its contents. The server returns the response body in gzip.
In general, the problem is that the data is read byte for a very long time, from 2 to 5 minutes.
c = new Socket("example.com", 80); PrintStream out = new PrintStream( c.getOutputStream() ); out.println("GET / HTTP/1.1"); out.println("Host: example.com"); out.println("User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0"); out.println("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); out.println("Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3"); out.println("Accept-Encoding: gzip, deflate"); out.println("Connection: keep-alive"); out.println(""); out.flush(); InputStream in = c.getInputStream(); byte[] buffer = new byte[8192]; // ByteArrayOutputStream ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΡΡΡ, ΠΊΠ°ΠΊ Π½Π°ΠΊΠΎΠΏΠΈΡΠ΅Π»Ρ Π±Π°ΠΉΡ, ΡΡΠΎΠ±Ρ // ΠΏΠΎΡΠΎΠΌ ΠΏΡΠ΅Π²ΡΠ°ΡΠΈΡΡ Π² ΡΡΡΠΎΠΊΡ Π²ΡΠ΅ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅. // ΠΏΡΠ΅ΠΎΠ±ΡΠ°Π·ΠΎΠ²ΡΠ²Π°ΡΡ ΡΠ°ΡΡΡ ΠΏΠΎΡΠΎΠΊΠ° Π² ΡΡΡΠΎΠΊΡ ΠΎΠΏΠ°ΡΠ½ΠΎ, Ρ.ΠΊ. // Π΅ΡΠ»ΠΈ Π΄Π°Π½Π½ΡΠ΅ ΠΈΠ΄ΡΡ Π² ΠΌΠ½ΠΎΠ³ΠΎΠ±Π°ΠΉΡΠ½ΠΎΠΉ ΠΊΠΎΠ΄ΠΈΡΠΎΠ²ΠΊΠ΅, ΠΎΠ΄ΠΈΠ½ ΡΠΈΠΌΠ²ΠΎΠ» ΠΌΠΎΠΆΠ΅Ρ // Π±ΡΡΡ ΡΠ°Π·ΡΠ΅Π·Π°Π½ ΠΌΠ΅ΠΆΠ΄Ρ ΡΡΠ΅Π½ΠΈΡΠΌΠΈ ByteArrayOutputStream baos = new ByteArrayOutputStream(); // InputStream.read( byte[] ) Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΏΡΠΎΡΠΈΡΠ°Π½Π½ΡΡ
Π±Π°ΠΉΡ // ΠΈ -1, Π΅ΡΠ»ΠΈ ΠΏΠΎΡΠΎΠΊ ΠΊΠΎΠ½ΡΠΈΠ»ΡΡ (ΡΠ΅ΡΠ²Π΅Ρ Π·Π°ΠΊΡΡΠ» ΡΠΎΠ΅Π΄ΠΈΠ½Π΅Π½ΠΈΠ΅) for ( int received; (received = in.read( buffer )) != -1; ) { // Π·Π°ΠΏΠΈΡΡΠ²Π°Π΅ΠΌ ΠΏΡΠΎΡΠΈΡΠ°Π½Π½ΠΎΠ΅ ΠΈΠ· ΠΏΠΎΡΠΎΠΊΠ°, ΠΎΡ 0 Π΄ΠΎ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²Π° ΡΡΠΈΡΠ°Π½Π½ΡΡ
baos.write( buffer, 0, received ); } // ΠΏΡΠ΅ΠΎΠ±ΡΠ°Π·ΡΠ΅ΠΌ Π² ΡΡΡΠΎΠΊΡ ( ΠΊΠΎΠ΄ΠΈΡΠΎΠ²ΠΊΡ ΠΆΠ΅Π»Π°ΡΠ΅Π»ΡΠ½ΠΎ ΡΠΊΠ°Π·ΡΠ²Π°ΡΡ ) String reply = baos.toString( "UTF-8" ); // ΠΌΠΎΠΆΠ½ΠΎ ΡΠ°ΠΊ, Π½ΠΎ toByteArray() ΡΠΎΠ·Π΄Π°Π΅Ρ ΠΊΠΎΠΏΠΈΡ ΠΌΠ°ΡΡΠΈΠ²Π°, Π° Ρ Ρ ΠΌΠ°ΠΌΡ ΠΎΠΏΡΠΈΠΌΠΈΠ·Π°ΡΠΎΡ //String reply = new String( baos.toByteArray(), StandardCharsets.UTF_8 ); System.out.println( reply ); c.close(); If I read through BufferedReader, then only headers from the web server come back. But much faster than the previous method, almost instantly.
BufferedReader br = new BufferedReader(new InputStreamReader(in)); while(true) { String line = br.readLine(); if(line.isEmpty()) break; } Tell me how to correctly read the response body from the server?
Connection: closeheader), although it is strange that it takes you minutes, my server turns off seconds after 5. The second method stops the cycle, encountering empty line, which, according to the standard, the title is separated from the content. Than you are not satisfied with the standardHttpURLConnectionand other http-clients on java? - zRrrIOUtils.toByteArray(inputStream);to read the whole stream. measure the result - Senior PomidorInputStream in = c.getInputStream(); byte[] bytes = IOUtils.toByteArray(in); System.out.println(new String(bytes, "UTF-8")); c.close();- or_die