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

更多相关文章

  1. android第四天早:多线程基础
  2. SQLite数据库并发访问
  3. Android(安卓)8.0无法调用Geocoder 中的getFromLocation()解决办
  4. Android面试题总结(七)原理篇
  5. Android基于Handler实现倒计时
  6. 【Android(安卓)Socket专题】:UDP通信客户端app的demo的实现
  7. Android(安卓)获取系统日期时间并且不断更新,类似时钟
  8. Android中利用画图类和线程画出闪烁的心形
  9. Android(安卓)ANR 探索

随机推荐

  1. 数据库管理中19个MySQL优化方法
  2. MySQL使用的常见问题解决与应用技巧汇总
  3. MySQL中索引与视图的用法与区别详解
  4. MySQL中参数sql_safe_updates在生产环境
  5. mysql5.7.17在win2008R2的64位系统安装与
  6. centos上安装mysql并设置远程访问的操作
  7. 详解MySQL中EXPLAIN解释命令及用法讲解
  8. mysql 无法联接常见故障及原因分析
  9. MySQL使用中遇到的问题记录
  10. MySQL百万级数据分页查询优化方案