使用httpclient有一种方法来获取带有HEAD请求的页面的字符集吗?

我正在使用httpclient库做一个基本的HEAD请求。 我很好奇我怎么能得到apache返回的字符集Eg:utf-8,iso-8859-1等等…谢谢!

HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 2000); HttpConnectionParams.setSoTimeout(httpParams, 2000); DefaultHttpClient httpclient = new DefaultHttpClient(httpParams); httpclient.getParams().setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); HttpContext localContext = new BasicHttpContext(); httpget = new HttpHead(url); HttpResponse response = httpclient.execute(httpget, localContext); this.sparrowResult.statusCode = response.getStatusLine().getStatusCode(); 

工作结果更新

 Header contentType = response.getFirstHeader("Content-Type"); String charset= contentType.getValue(); 

在HTTP 1.1中,字符集位于Content-Type标头中

 HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 

所以这应该被埋没

 HttpResponse.Headers 

所以,这应该工作

 HttpResponse.Headers.["Content-Type"] 

**没有测试这个,但你明白了

如果使用HttpClient 4.2

 import java.nio.charset.Charset; import org.apache.http.entity.ContentType; ContentType contentType = ContentType.getOrDefault(entity); Charset charSet = contentType.getCharset(); 

如果使用HttpClient 4.1(最新):

 import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } 

在某些情况下,服务器不会在标题中为您提供字符集,但会在内容中写入,例如此URL: http : //seniv.dlmostil.ru/jacket/p/kupit-sportivnie-bryki-adidas-s-dostavkoy /

当你这样做

 ContentType contentType = ContentType.getOrDefault(entity); Charset charSet = contentType.getCharset(); 

然后charSet为null

在这种情况下,我读取流并尝试使用正则表达式从html代码中提取charSet,因此当您从输入流中读取内容时

 ByteArrayOutputStream out = new ByteArrayOutputStream(); 

然后你可以这样做:

 String help = new String(out.toByteArray()); Pattern charSet = Pattern.compile("charset\\s*=\\s*\"?(.*?)[\";\\>]", Pattern.CASE_INSENSITIVE); Matcher m = charSet.matcher(help); String encoding = m.find() ? m.group(1).trim() : "UTF-8"; if (Charset.availableCharsets().get(encoding) == null) encoding = Charsets.UTF_8.toString(); String html = new String(out.toByteArray(), encoding); 

当所有其他方法都不起作用时,我希望你能理解这个最后一个出口。