a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 70|回复: 0

[其他] JAVA技巧:java抓取网页内容生成静态页面

[复制链接]
发表于 2012-8-4 12:28:23 | 显示全部楼层 |阅读模式
private static String getStaticPage(String surl) {              String htmlContent = "";
( |0 I) y, v3 a  V6 s             try {9 T2 K* L. j, t, a' t
                java.io.InputStream inputStream;
  V+ s/ ]8 X" U, B9 A                java.net.URL url = new java.net.URL(surl);
8 y3 D, b6 A! w0 B                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();9 e; ]' R8 m1 M$ m2 e3 y, t
                connection.connect();" s4 I4 V7 E5 F) R# w
                inputStream = connection.getInputStream();* s9 Q6 K, j* B
                byte bytes[] = new byte[1024 * 2000];# _% ]0 |* O, B# P7 E/ l
                int index = 0;. K8 g& J& q, n+ F4 b& p& s) H
                int count = inputStream.read(bytes, index, 1024 * 2000);* d7 o+ H1 x$ S: S( _
                while (count != -1) {' z9 p! \! J2 }  [/ {2 e
                    index += count;" D: f6 O. S5 O1 z7 H; ]
                    count = inputStream.read(bytes, index, 1);
; X7 L8 x8 [' U( V, v; ^; I* o& h                }3 X1 B8 r8 Z1 P) D( N: y9 T
                htmlContent = new String(bytes, "UTF-8");
) j  b. C% n. F                connection.disconnect();
4 H7 r1 L5 b9 ]/ r. k             } catch (Exception ex) {
1 Z7 v1 a0 L& I6 ~! B9 i, ]4 ]                ex.printStackTrace();  w" X0 G9 x0 {" M* W' t# x
             }
( G/ K: O) o+ A7 c% \( [$ B( s3 q1 B             return htmlContent.trim();- M; N7 P3 ~& F6 {3 q8 F) F/ m
         }
# O2 f1 f2 p5 X; O- J5 ^# O  
/ b1 S$ h! D. R9 ]" i     String src= getStaticPage(“http://www.google.com”);8 A. v2 c& d9 D
         File file = new File(“d:aa.html”);. X1 x% f5 j4 M! x- Q0 x
         FileWriter resultFile = new FileWriter(file); & D& `  i8 M* H% t7 ?: j
         PrintWriter myFile = new PrintWriter(resultFile); ( C" A" T; x  w5 ~+ N3 U! Z. S3 E" e
         //写文件8 a$ L3 Y4 g' G& v% f0 {
         myFile.println(src); 8 \# R; ~/ E+ k5 K
         resultFile.close();
0 o8 U$ b1 |, {8 E2 G: s         myFile.close();
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-5-22 05:15 , Processed in 0.189909 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表