java inputstream print来控制内容

时间:2009-07-05 08:23:01

标签: java servlets httpwebrequest

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

3 个答案:

答案 0 :(得分:19)

如果要打印网页内容,则需要使用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示例,取自here

   // 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();
    }  

答案 1 :(得分:1)

如果你要获取网页的内容,你应该看看apache httpclient而不是自己编码,期望用于学习目的或任何其他非常好的理由。

答案 2 :(得分:1)

使用Java 8 Stream API从Stream创建String非常容易:

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

使用IntelliJ我甚至可以将这个设置为调试表达式: enter image description here

我想Eclipse中的工作方式类似。