下午好。我想从站点获取数据,为此我使用 Apache HttpComponents。请求是这样的:
public Header[] sendRequest() throws IOException {
CloseableHttpResponse responsePost = null;
HttpPost httpPost;
httpPost = new HttpPost(urlForRequest);
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
responsePost = httpClient.execute(httpPost);
HttpEntity entityPost = responsePost.getEntity();
sourceTextFile = EntityUtils.toString(entityPost);
responsePost.close();
return responsePost.getHeaders("Location");
}
请求页面文本时抛出异常
15:39:20,061 ERROR [stderr] java.nio.charset.IllegalCharsetNameException: America/New_York
Заголовок ответа содержит ошибочные данные
Connection : close
Content-Encoding: gzip
Content-Length: 20
Content-Type: text/html; charset=America/New_York
Date : Thu, 13 Oct 2016 12:41:28 GMT
站点返回的Content-Type为text/html;字符集=美国/纽约。正因为如此,线上
sourceTextFile = EntityUtils.toString(entityPost);
我得到一个例外。
如何在收到不正确的 ContentType 标头时将页面内容读入文件?
发生错误是因为方法
EntityUtils.toString()在读取实体时使用来自响应 http 标头的编码并抛出java.nio.charset.IllegalCharsetNameException,因为它America/New_York不是有效的编码(和一般编码)。要解决此错误,您可以使用
entityPost.getContent().