問題:用 android 4.4 寫android訪問http時,到connection.getResponseCode() 就不被執行,也不報錯。如下面紅色字型:
public static String getJsonContent(String url_path ,String encode){String jsonString = "";try {URL url = new URL(url_path);HttpURLConnection connection = (HttpURLConnection)url.openConnection();connection.setConnectTimeout(3000);connection.setRequestMethod("GET");connection.setDoInput(true); //從伺服器獲得資料int responseCode = connection.getResponseCode(); if (200 == responseCode) {jsonString = changeInputStream(connection.getInputStream(),encode);}} catch (Exception e) {// TODO: handle exception}//return jsonString;}private static String changeInputStream(InputStream inputStream , String encode) throws IOException {// TODO Auto-generated method stubString jsonString = null;ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;while((len=inputStream.read(data))!=-1){outputStream.write(data, 0, len);}jsonString = new String(outputStream.toByteArray(), encode);inputStream.close();return jsonString;}
此段代碼直接在java 工程裡是可以訪問http的,並且用瀏覽器直接存取 urp_path = http://192.168.0.102:8080/json_Project/servlet/JsonAction?action_flag=person 也是有相應的,證明url地址是對的。
解決方案:
原因:訪問HTTP的請求沒有放在單獨線程而是放在主線程了。
解決方案,把http的請求單獨放在一個新線程中,或者在調用此Http訪問的Activity的onCreat()方法內加:closeStrictMode().
public static void closeStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build());
}
參考文章:http://hb.qq.com/a/20110914/000054.htm