您的位置:首页 > 业界新闻

java 开发小记:WebClient,获取互联网资源(尤其需关注源的编码)

2009-10-19 14:57 555 查看
.csharpcode, .csharpcode pre
{
font-size: 12px;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
所有小记将本着简化编码细节的原则进行,以使得今后开发回避技术的冗余面,而更多关注业务逻辑!

这段代码将向你介绍几个比较常见但需要注意的问题:

1,尽量使用本地配置资源,比如 System.getProperty("line.separator") 代替手工输入 “\r\n”,以此解决跨平台问题(Windows、Mac等)。

2,如何利用程序读取互联网上的文本资源,以及注意其文本编码(Encoding,这是本文的要点)。

3,使用 StringBuilder 而不是“String 相加”获取一个较大的变长文本,这主要影响程序性能,而不是功能。

功能极其有限,但对于初学者肯定有其碰壁之处,使用该包装好的类,可使用如下方式获取互联网文本资源:

WebClient wc = new WebClient();
String s = wc.getContent("http://localhost:8088/index.jsp", "utf-8", null);
System.out.println(s);

如下是 WebClient 类的源码:

package queen.net;

import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class WebClient{

private static String _newLine = System.getProperty("line.separator");

public WebClient(){
}

public String getContent(String url, String oriEncoding, String targetEncoding) throws IOException{
URL u = new URL(url);
URLConnection uc = u.openConnection();
BufferedReader in;
if(oriEncoding == null || oriEncoding.length() == 0){
in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
}
else{
in = new BufferedReader(new InputStreamReader(uc.getInputStream(), oriEncoding));
}
String line;
StringBuilder sb = new StringBuilder();
while((line = in.readLine()) != null){
sb.append(line);
sb.append(_newLine);
}
if(targetEncoding == null || targetEncoding.length() == 0){
return sb.toString();
}
return new String(sb.toString().getBytes(), targetEncoding);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: