本人使用Tomcat apache-tomcat-8.0.28虛擬服務器,默認utf-8編碼
update.json
{"versionName":"2.0","versionCode":2,"description":"Hello word!!","downloadUrl":"http://www.baidu.com"}
android studio 1.3.1 做了個客戶端:部分編碼如下:
private void checkVersion(){
new Thread(){
@Override
public void run() {
try {
URL url = new URL("http://10.0.2.2:8080/update.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
int responseCode = conn.getResponseCode();
if(responseCode==200){
InputStream inputStream = conn.getInputStream();
String result = StreamUtils.readFromSteam(inputStream);
Log.e("System.Out.Print", "result:"+result);
//解析Json
JSONObject jo = new JSONObject(result);
mVersionName = jo.getString("versionName");
mVersionCode = jo.getInt("versionCode");
mDescription = jo.getString("description");
mDownloadUrl = jo.getString("downloadUrl");
Log.e("System.Out.Print", "run "+mVersionName+";"+mVersionCode);
Log.e("System.Out.Print", "run "+mDescription+";"+mDownloadUrl);
}
} catch (MalformedURLException e) {
// utl錯誤的異常
e.printStackTrace();
} catch (IOException e) {
//網絡錯誤的異常
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
public class StreamUtils {
/**
* readFromSteam() 將輸入流讀成String後返回
* @return
*/
public static String readFromSteam(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len=in.read())!=-1){
out.write(buffer,0,len);
}
String result = out.toString();
in.close();
out.close();
return result;
}
}
每次運行後的結果如下:
![圖片說明](http://img.ask.csdn.net/upload/201602/21/1456069188_115538.jpg)
請大神指點
在用HttpURLConnection的時候,沒有設置默認編碼,可能是utf-8和 "ISO-8859-1"混淆了。
然後模擬器和手機不一樣的原因是;Android版本不一樣導致HttpURLConnection的具體實現不一樣,記得Android4.4之後,HttpURLConnection底層采用HttpOK了。