標籤:
問題:用 android 4.4 寫android訪問http時,到connection.getResponseCode() 就不被執行,也不報錯:但是拋出org.json.JSONException: End of input at character 0 of .異常:
串連代碼:
public static String getJsonContent(String url_path){ try { System.out.println("url_path---->>:"+url_path); URL url=new URL(url_path); HttpURLConnection connetion=(HttpURLConnection)url.openConnection(); connetion.setConnectTimeout(3000); connetion.setRequestMethod("GET"); connetion.setDoInput(true); System.out.println("connetion---->>:"+connetion); int code=connetion.getResponseCode(); System.out.println("code---->>>:"+code); if (code==200){ return changeInputStream(connetion.getInputStream()); }else{ System.out.println("---->>請求碼不正確!!!"); return ""; } } catch (Exception e) { e.printStackTrace(); } return "";}View Code
此段代碼直接在java 工程裡是可以訪問http的,並且用瀏覽器直接存取 url_path=http://192.168.111.102:8080/jsonproject/servlet/JsonAAction?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
android中Http訪問時 connection.getResponseCode()不被執行,且報錯 org.json.JSONException: End of input at character 0 of .