(String link)
| 143 | *(2)从主体中匹配获取:"charset" |
| 144 | * */ |
| 145 | public static String getCharset(String link) { |
| 146 | String charset = "utf-8"; |
| 147 | |
| 148 | HttpURLConnection conn = null; |
| 149 | |
| 150 | try { |
| 151 | URL url = new URL(link); |
| 152 | |
| 153 | conn = (HttpURLConnection)url.openConnection(); |
| 154 | |
| 155 | conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"); |
| 156 | |
| 157 | conn.connect(); |
| 158 | System.setProperty("sun.net.client.defaultConnectTimeout","30000"); |
| 159 | System.setProperty("sun.net.client.defaultReadTimeout", "30000"); |
| 160 | |
| 161 | String contentType = conn.getContentType(); |
| 162 | |
| 163 | //在header里面找charset |
| 164 | |
| 165 | charset = findCharset(contentType); |
| 166 | //System.out.println("header:"+charset); |
| 167 | |
| 168 | //如果没找到的话,则一行一行的读入页面的html代码,从html代码中寻找 |
| 169 | |
| 170 | if(charset.isEmpty()){ |
| 171 | BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); |
| 172 | |
| 173 | String line = reader.readLine(); |
| 174 | |
| 175 | while(line != null) { |
| 176 | if(line.contains("Content-Type")) { |
| 177 | // result = findCharset(line); |
| 178 | Pattern p = Pattern.compile("content=\"text/html;\\s*charset=([^>]*)\""); |
| 179 | Matcher m = p.matcher(line); |
| 180 | if (m.find()) { |
| 181 | charset = m.group(1); |
| 182 | System.out.println("html:"+charset); |
| 183 | } |
| 184 | break; |
| 185 | |
| 186 | } |
| 187 | |
| 188 | line = reader.readLine(); |
| 189 | |
| 190 | } |
| 191 | reader.close(); |
| 192 | |
| 193 | } |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | } catch (Exception e) { |
| 199 | // TODO Auto-generated catch block |
| 200 | //这里可以打印响应不了的域名错误信息 |
| 201 | //e.printStackTrace(); |
| 202 |
no test coverage detected