Android解析socket或http流中文编码问题

来源:互联网 发布:美丽岛事件知乎 编辑:程序博客网 时间:2024/04/28 20:09

这里直接拿了HTTP流实验了下

Java代码
  1. public String getHttpContent(String htmlUrl) throws IOException,   
  2.    InterruptedException {   
  3.   URL url;   
  4.   InputStream is = null;   
  5.   HttpURLConnection urlConn = null;   
  6.   int count = 0;   
  7.   ByteArrayOutputStream baos = new ByteArrayOutputStream();   
  8.   try {   
  9.    url = new URL(htmlUrl);   
  10.    urlConn = (HttpURLConnection) url.openConnection();   
  11.   
  12.    urlConn.setConnectTimeout(20000);   
  13.    urlConn.setReadTimeout(20000);   
  14.    is = urlConn.getInputStream();   
  15.   
  16.    byte[] buf = new byte[512];   
  17.    int ch = -1;   
  18.    while ((ch = is.read(buf)) != -1) {   
  19.     baos.write(buf, 0, ch);   
  20.     count = count + ch;   
  21.    }   
  22.   
  23.   } catch (final MalformedURLException me) {   
  24.    me.getMessage();   
  25.    throw me;   
  26.   } catch (final IOException e) {   
  27.    e.printStackTrace();   
  28.    throw e;   
  29.   }   
  30.    return new String(baos.toByteArray(), "GB2312");   
  31.  }   
  32.   

其实上面的方法很简单,刚开始那哥们用的BufferedReader去读,这样直接读出来String有问题,解码不对,后来自己读到 byteoutputstream里,然后读出字节自己手工编码就对了,可是昨天晚上发现了一个更简单的方法,我们真是走了一个大大的弯路,如下:

Java代码
  1. public String getHttpContent(String htmlurl) throws Exception{   
  2.   HttpClient hc = new DefaultHttpClient();   
  3.   
  4.   HttpGet get = new HttpGet(htmlUrl);   
  5.   HttpResponse rp = hc.execute(get);   
  6.   
  7.   if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
  8.   
  9.   return EntityUtils.toString(rp.getEntity()).trim();   
  10.   
  11.   }else{   
  12.   
  13.   return null;   
  14.   
  15.   }   
  16.   
  17. }   

apache的这些类用起来还真是方便,以后还要多多学习。

原创粉丝点击