2018年6月24日 星期日

取得網頁上的字串,UTF8亂碼轉BIG5

       
//取得網頁上的字串
HttpURLConnection conn=null;
        try {
            URL httpUri = new URL(url);
            conn = (HttpURLConnection) httpUri.openConnection();
            conn.setReadTimeout(1500); //设置从主机读取数据超时(单位:毫秒)
            conn.setConnectTimeout(1500); //设置连接主机超时(单位:毫秒)
            conn.setRequestProperty("Content-Type","UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            final StringBuffer sb = new StringBuffer();
    //若網頁是BIG5,android預設UTF-8 讀下來會出現亂碼,這邊要設置為BIG5解決亂碼
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"BIG5"));
            String str;
            while((str = reader.readLine()) != null)
            { sb.append(str); }
            Log.d("Deubg",sb.toString());
            allString =sb.toString();
            reader.close();//關閉IO和連結
            conn.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(conn!=null)
                conn.disconnect();
        }

沒有留言:

張貼留言