android中Http訪問時 connection.getResponseCode()不被執行

來源:互聯網
上載者:User

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.