a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 99|回复: 0

[其他] JAVA技巧:WebClient获取互联网资源

[复制链接]
发表于 2012-8-4 12:28:23 | 显示全部楼层 |阅读模式
这段代码将向你介绍几个斗劲常见但需要注重的问题:   1,尽量使用当地设置装备摆设资本,好比 System.getProperty("line.separator") 庖代手工输入 “rn”,以此解决跨平台问题(Windows、Mac等)。( K9 J0 w9 T. S& M" T
  2,若何操作轨范篡夺互联网尚罾υ本资本,以及注重其文本编码(Encoding,这是本文的要点)。
/ ^. J. d) G4 I3 h, l0 h  3,使用 StringBuilder 而不是“String 相加”获取一个较年夜的变长文本,这首要影响轨范机能,而不是功能。" i% }. R8 {1 |/ t% ~0 m& k& |
  功能极其有限,但对于初学者必定有其碰钉子之处,使用该包装好的类,可使用如下体例获取互联网文本资本:
4 [, f/ u4 W+ O% q1 ^$ G% Q  WebClient wc = new WebClient();
; T* f  c1 P; M$ g  String s = wc.getContent("http://localhost:8088/index.jsp", "utf-8", null); System.out.println(s);
: m3 Q" D! ~3 {) {. b5 z5 c  如下是WebClient类的源码:! U. i  K! n! v% F9 O
  package queen.net;- G" Z; I2 X, b3 o# m; A" S
  import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
$ h( q2 B! z- W) m2 Z  public class WebClient{
9 A* a$ i4 d  L+ u  private static String _newLine = System.getProperty("line.separator");
0 p5 Q+ j! i. t% i1 K# j0 _8 s  public WebClient(){8 r6 Z' L' g" s9 ?6 C; ^6 C% K
  }
" F/ i6 ?1 _- p+ {/ f* m  public String getContent(String url, String oriEncoding, String targetEncoding) throws IOException{. \. l3 g' ]- z% _& j6 ]5 a9 D
  URL u = new URL(url);
2 x. O" [7 u8 U) E' k% a3 b2 f' `  URLConnection uc = u.openConnection();( D' Z* H6 I1 r: `/ I$ e
  BufferedReader in;
* e% c: l. ]9 `" z. ?- J4 i  if(oriEncoding == null || oriEncoding.length() == 0){ in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
$ B1 ?& H) V* Z) P  }" T8 {* i2 L& U# P6 ^
  else{/ k$ E4 \, w( l* y$ `! D8 _/ u% l2 C8 \
  in = new BufferedReader(new InputStreamReader(uc.getInputStream(), oriEncoding));
. Y( ?$ z+ @1 k$ w) Z4 W: F* C$ M  }9 Z. F* z: |: w8 |' L5 T$ l2 n, s! p
  String line;
( j- L& G! B" \: y  StringBuilder sb = new StringBuilder();: H+ M3 n' I& V3 F7 X4 v
  while((line = in.readLine()) != null){ sb.append(line); sb.append(_newLine);& }# ^  I' Q( E7 Z: F8 S
  }
" W7 l2 \, a* A; ~. B  if(targetEncoding == null || targetEncoding.length() == 0){ return sb.toString();) a0 g; ]. b: W' {: L7 a
  }
7 o% ^) }' S# f9 s9 }" M% @  return new String(sb.toString().getBytes(), targetEncoding);
3 K6 q+ W6 B1 c/ z# r9 P! ?  }, z! K1 w8 Y  }9 c% X; M4 x2 T
  }
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-4 12:32 , Processed in 0.224052 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

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