標籤:null pre image address 分數 ide write length res
樓主前段時間做android項目,用到http通訊,於是樓主本著練手的態度,自己寫httpUrlConnection通訊過程,然後在測試的時候,發現使用post請求一直亂碼,這時候樓主開始看發送的資料,發現發送的資料是正確的,沒有亂碼,是utf-8的,然後又看伺服器的代碼,沒錯,也進行了轉碼的操作,那麼,到底是哪出問題了呢?這個困擾了樓主好久,後來,樓主無意中發現,書中(第一行代碼)進行通訊時,post請求資料使用的是如下代碼:
ad(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(data.getBytes()); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line=reader.readLine())!=null) { response.append(line); }
然而樓主在使用out.write(data.getBytes())時,寫成了out.writeBytes(data)。可以說是非常微小的一個差別,那麼當樓主將這行代碼改完後,進行測試,發現亂碼問題解決了,然後樓主就蒙了,什麼鬼,這有兩函數有區別嗎???後來樓主查閱資料,發現這兩函數的確有非常非常大的區別。
前者是將data(string類型)轉換為byte數組,然後傳輸。這個是沒有問題的。那後者是怎麼轉換的呢,看下其原始碼:
這時候問題出現了,看s.length();對於中文,獲得長度是字的長度,以下是驗證:
、
我們都知道,漢字的儲存都是兩個位元組的,但是獲得長度是3個,所以進行強轉必定會出現截取調一部分資料,因此亂碼,以下是實驗:
android http通訊之HttpURLConnection post亂碼問題