首页 > 代码库 > 使用java.net.URL获取网页编码
使用java.net.URL获取网页编码
在同一个类中
需要导入以下的包:
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
1 @Test 2 public void e() throws MalformedURLException, IOException{ 3 System.out.println(testgetCharset()); 4 } 5 public String testgetCharset() throws MalformedURLException, IOException{ 6 /** 7 * 获取一个网页的编码形式 8 * 9 * @param url10 */11 String host="proxy3.bj.petrochina";12 String port="8080"; 13 setProxy(host,port);14 String url="http://www.songtaste.com";15 URLConnection uc = new URL(url).openConnection();16 uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");17 18 InputStream is = uc.getInputStream();19 BufferedReader br = new BufferedReader(new InputStreamReader(is));20 String str = new String();21 String temp = null;22 int i = 0;23 while ((temp = br.readLine()) != null)24 {25 str += temp;26 if (temp.length()>6 && temp.substring(0, 6).equals("<body>"))27 break;28 if (++i > 50)29 break;30 }31 br.close();32 33 //比较等于charset,然后找出charset的值34 for (i=0; i<str.length()-7; i++) 35 {36 if (str.substring(i, i+7).equalsIgnoreCase("charset"))37 {38 i = i+7;39 break;40 }41 }42 int begin = 0;43 while (true) 44 {45 if (i >= str.length())46 return new String();47 char c = str.charAt(i);48 if (c!=‘ ‘ && c!=‘=‘)49 {50 if (begin == 0)51 begin = i;52 if (c == ‘"‘)53 return str.substring(begin, i);54 }55 i++;56 }57 }58 59 public static void setProxy(String host, String port) { 60 System.setProperty("proxySet", "true"); 61 System.setProperty("proxyHost", host); 62 System.setProperty("proxyPort", port); 63 }
使用java.net.URL获取网页编码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。