使用apache的HttpGet\HttpPost获取返回内容编码问题
今天遇到了一個(gè)小問(wèn)題,簡(jiǎn)單研究了一下,同時(shí)記錄一下。
關(guān)于apache的HttpGet\HttpPost請(qǐng)求,做了一次訪問(wèn),代碼如下:
String url = "http://xxxxxxx";HttpGet httpGet = new HttpGet(url);HttpClient httpClient = new DefaultHttpClient();try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity();//String result = EntityUtils.toString(httpEntity, "utf-8");InputStream is = null;is = httpEntity.getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(is));String result = "";String line = "";while ((line = reader.readLine()) != null) {result = result + line;}System.out.println(result);} catch (Exception e) {e.printStackTrace();}?結(jié)果出現(xiàn)了亂碼。立刻對(duì)代碼進(jìn)行修改BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
依舊出現(xiàn)亂碼,到底是哪里出問(wèn)題?
如果用第7行的方式來(lái)獲取的話就不會(huì)有亂碼。
第7行的方法很簡(jiǎn)單,深入研究下實(shí)際上也是獲取流進(jìn)行處理,只是在過(guò)程中加入了編碼處理,那么到底是怎么處理的?
該方法源碼如下:
public static String toString(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {if (entity == null) {throw new IllegalArgumentException("HTTP entity may not be null");}InputStream instream = entity.getContent();if (instream == null) {return "";}if (entity.getContentLength() > Integer.MAX_VALUE) {throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");}int i = (int)entity.getContentLength();if (i < 0) {i = 4096;}String charset = getContentCharSet(entity);if (charset == null) {charset = defaultCharset;}if (charset == null) {charset = HTTP.DEFAULT_CONTENT_CHARSET;}Reader reader = new InputStreamReader(instream, charset);CharArrayBuffer buffer = new CharArrayBuffer(i);try {char[] tmp = new char[1024];int l;while((l = reader.read(tmp)) != -1) {buffer.append(tmp, 0, l);}} finally {reader.close();}return buffer.toString();}?可以看見(jiàn)是在InputStreamReader這里處理的。和我處理的地方是一致的,那么還有什么問(wèn)題?
后來(lái)仔細(xì)一看發(fā)現(xiàn)toString()方法傳入的編碼方式未必就是最后使用的,這中間還有個(gè)判斷,就是判斷HttpEntity返回的header是否存在charset,不存在才會(huì)使用傳入的參數(shù)。
本來(lái)我一直認(rèn)為這個(gè)參數(shù)就應(yīng)該是utf-8,結(jié)果用EntityUtils的getContentCharSet方法一獲取才發(fā)現(xiàn)是GBK。。。
這下就清楚了,修改代碼BufferedReader reader = new BufferedReader(new InputStreamReader(is, "gbk"));
這回不是亂碼了,不過(guò)這部分應(yīng)該在前面做好判斷,先用getContentCharSet獲取一下,如果是空再自己設(shè)定一個(gè)才好。
至于getContentCharSet方法如何實(shí)現(xiàn)的,代碼如下:
public static String getContentCharSet(final HttpEntity entity)throws ParseException {if (entity == null) {throw new IllegalArgumentException("HTTP entity may not be null");}String charset = null;if (entity.getContentType() != null) {HeaderElement values[] = entity.getContentType().getElements();if (values.length > 0) {NameValuePair param = values[0].getParameterByName("charset");if (param != null) {charset = param.getValue();}}}return charset;}??
總結(jié)
以上是生活随笔為你收集整理的使用apache的HttpGet\HttpPost获取返回内容编码问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Fragment的布局中自定义Layou
- 下一篇: 使用View的getWidth(),ge