赞
踩
- package catchutr;
-
- /**
- *
- * @Description:HttpURLConnection获取网页文字并保存到本地 对比字符串打印并保存
- * @Title: UrlHttp.java
- * @Package catchutr
- * @version V1.0
- * @author luoyang QQ1845313665
- * @date 2020年5月7日下午5:26:34
- *
- */
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
-
- import org.omg.CORBA.portable.InputStream;
-
- public class UrlHttp {
-
- /**
- * @param args
- */
- public static void main(String args[]) {
-
-
- String s1="http://www.ltsw888.com/book_208/";
-
- try {
- //实例化一个URL对象
- URL url = new URL(s1);
- //用于创建HttpURLConnection
- HttpURLConnection connect = (HttpURLConnection) url.openConnection();
- //设置为GET方式请求数据
- connect.setRequestMethod("GET");
- //设置3秒的响应超时
- connect.setConnectTimeout(6000);
- //获取连接,连接响应码为200,表示连接成功
- connect.connect();
- int code=connect.getResponseCode();
- System.out.println("--------------------------------------"+code);
-
- if(code ==200) {
- //获取服务端返回的数据流
- java.io.InputStream in = connect.getInputStream();
-
-
- int num = 0;
- FileOutputStream fos = new FileOutputStream(new File("D:\\yest.html"));
-
- byte bytes[] =new byte[1*1024];
- int readSize =-1;
-
- while((readSize = in.read(bytes))!=-1){
- //写入文件
- fos.write(bytes, 0, readSize);
- System.out.print((num++)+"-");
- }
- //关闭流
- fos.close();
-
- //转成字符串打印并保存
-
- // //读取流,并设置编码格式
- // InputStreamReader read = new InputStreamReader(connect.getInputStream(),"UTF-8");
- // //InputStreamReader read = new InputStreamReader(connect.getInputStream());
- //
- // //储存在BufferedReader中,并打印地址值
- // BufferedReader buffer = new BufferedReader(read);
- // System.out.println(buffer.toString());
- //
- // //新建String字符串存储实例,
- // StringBuffer buf = new StringBuffer();
- //
- // //该代码块注释,上一个while与下一个while语句有冲突
- // String line = null;
- // while((line=buffer.readLine())!=null) {
- // //装在进String字符串,
- // buf.append(line);
- // //打印每一行的Buffered
- // System.out.println(line);
- // }
- //
- // //把字符串buffer写入文件 写入可能会乱码
- // FileWriter fos1 = new FileWriter(new File("D:\\yest1.html"));
- // fos1.write(buf.toString());
- // fos1.close();
- //
- // //关闭各种流
- // buffer.close();
- // read.close();
-
- in.close();
-
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
一个程序员的自我修养和成长........
在这里可以找到我,微信公众号。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。