簡體   English   中英

java inputstream 打印以控制內容

[英]java inputstream print to console the content

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?
 }

如果要打印網頁的內容,則需要使用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();
    }  

使用 Java 8 Stream API 從流創建字符串非常容易:

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

使用 IntelliJ 我什至可以將此 bee 設置為調試表達式: 在此處輸入圖片說明

我想在 Eclipse 中它的工作方式類似。

如果您要獲取網頁的內容,您應該看看apache httpclient而不是自己編寫代碼,期望用於學習目的或任何其他真正好的理由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM