android中Http访问时 connection.getResponseCode()不被执行

来源:互联网 发布:linux基础知识总结 编辑:程序博客网 时间:2024/04/30 09:10

问题:用 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


0 0
原创粉丝点击