六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 33|回复: 0

java获取网页的编码方式

[复制链接]

升级  72%

6

主题

6

主题

6

主题

童生

Rank: 1

积分
36
 楼主| 发表于 2013-2-3 10:33:25 | 显示全部楼层 |阅读模式
public static String getEncoding(HttpURLConnection httpUrlConnection) throws IOException{
String contentEncoding=httpUrlConnection.getContentEncoding();
String contentType=httpUrlConnection.getContentType();
InputStream inputStream=httpUrlConnection.getInputStream();
if(contentEncoding==null){

int index=contentType.indexOf("=");
if(index==-1){
System.out.println("----contentType----");
return getEncodingByInputStream(inputStream);
}else{
System.out.println("----InputStream----");
String t=contentType.substring(index+1);
return t.toUpperCase();
}
}else{
System.out.println("----contentEncoding----");
return contentEncoding;
}
}
public static String getEncodingByInputStream(InputStream inputStream){
try {
StringBuffer sb=new StringBuffer("1234567");
StringBuffer sb2=new StringBuffer();
int t;
while ((t=inputStream.read())!=-1) {
sb.deleteCharAt(0);
sb.append((char)t);
if(sb.toString().toLowerCase().equals("charset")){
for (int i = 0; i < 10; i++) {
char c=(char) inputStream.read();
sb2.append(c);
}
break;
}

}
String str=sb2.toString();
int si=str.indexOf("=")+1;
int ei=str.indexOf("\"");
String encoding=str.substring(si, ei).trim().toUpperCase();
return encoding;
} catch (IOException e) {
e.printStackTrace();
return "UTF-8";
}
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

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