Android解析socket或http流中文編碼問題

這裏直接拿了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的這些類用起來還真是方便,以後還要多多學習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章