Http请求返回结果报UnsupportedCharsetException
最近在Http请求时,出现了Caused by: java.nio.charset.UnsupportedCharsetException: The unsupported charset name is "GB18030".
不支持GB18030
会出现这种问题,是由于我采用了EntityUtils.toString方法来解析回传数据。那么在这里会涉及到charset。
那么,先来看看如何取得response中的charset
HttpEntity entity = httpResponse.getEntity();Header header = entity.getContentType();if (header != null) {HeaderElement[] elements = header.getElements();if (elements.length > 0) {String name = elements[0].getName();String charset = null;NameValuePair param = elements[0].getParameterByName("charset");if (param != null) {charset = param.getValue();}Charset c = (charset != null && charset.length() > 0) ? Charset.forName(charset) : null;System.out.println(c.name());}}
再来看看charset说明中,其所支持的:The following charsets should be supported by any java platform: US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16.
所以,如果返回来的是GB18030,自然就不支持了
解决的方法:
用下面这个方法代替EntityUtils.toString
public Object handleEntity(HttpEntity entity, String charset)throws IOException {if (entity == null)return null;ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];long count = entity.getContentLength();long curCount = 0;int len = -1;InputStream is = entity.getContent();while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);curCount += len;}byte[] data = outStream.toByteArray();outStream.close();is.close();return new String(data, charset);}