android中Http访问时 connection.getResponseCode()不被执行
16lz
2021-01-24
问题:用 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
更多相关文章
- android第四天早:多线程基础
- SQLite数据库并发访问
- Android(安卓)8.0无法调用Geocoder 中的getFromLocation()解决办
- Android面试题总结(七)原理篇
- Android基于Handler实现倒计时
- 【Android(安卓)Socket专题】:UDP通信客户端app的demo的实现
- Android(安卓)获取系统日期时间并且不断更新,类似时钟
- Android中利用画图类和线程画出闪烁的心形
- Android(安卓)ANR 探索