java输入流的控制_java输入流打印到控制台的内容

如果要打印网页的内容,则需要使用

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头并检查来保存流量

内容编码头的响应.

这是一个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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值