Java inputstream print для консоли содержимого

sock = new Socket("www.google.com", 80);
       out  = new BufferedOutputStream(sock.getOutputStream());
       in   = new BufferedInputStream(sock.getInputStream());

Когда я пытаюсь распечатать содержимое внутри "in", как показано ниже

 BufferedInputStream bin = new BufferedInputStream(in);
 int b;
 while ( ( b = bin.read() ) != -1 )
 {

     char c = (char)b;         

     System.err.print(""+(char)b); //This prints out content that is unreadable.
                                   //Isn't it supposed to print out html tag?
 }

Ответы

Ответ 1

Если вы хотите распечатать содержимое веб-страницы, вам необходимо работать с протоколом HTTP. Вам не нужно реализовывать его самостоятельно, лучший способ - использовать существующие реализации, такие как java API HttpURLConnection или Apache HttpClient

Вот пример того, как это сделать с HttpURLConnection:

URL url = new URL("http","www.google.com");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setAllowUserInteraction( false );
urlc.setDoInput( true );
urlc.setDoOutput( false );
urlc.setUseCaches( true );
urlc.setRequestMethod("GET");
urlc.connect();
// check you have received an status code 200 to indicate OK
// get the encoding from the Content-Type header
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line = null;
while((line = in.readLine()) != null) {
  System.out.println(line);
}

// close sockets, handle errors, etc.

Как указано выше, вы можете сохранить трафик, добавив заголовок Accept-Encoding и проверив  Заголовок Content-Encoding ответа.

Вот пример HttpClient, взятый из здесь:

   // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  

Ответ 2

Если вы хотите получить содержимое веб-страницы, вы должны взглянуть на apache httpclient вместо того, чтобы кодировать это самостоятельно, ожидайте учебных целей или любой другой действительно веской причины.

Ответ 3

Очень просто создать строку из потока с использованием Java 8 Stream API:

new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"))

Используя IntelliJ, я даже могу установить это в качестве отладочного выражения: введите описание изображения здесь

Я предполагаю, что в Eclipse он будет работать аналогично.