android中Http訪問時 connection.getResponseCode()不被執行,且報錯 org.json.JSONException: End of input at character 0 of .

來源:互聯網
上載者:User

標籤:

問題:用 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 .

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.