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
- android中Http访问时 connection.getResponseCode()不被执行
- android中Http访问时 connection.getResponseCode()不被执行
- android中Http访问时 connection.getResponseCode()不被执行
- Android学习日志: 执行.getResponseCode()方法时出现错误常
- android中HttpURLConnection调用getResponseCode()时崩溃 解决方法
- Android 中访问HTTP
- 解析 HTTP(HttpURLConnection getResponseCode)
- 解析 HTTP(HttpURLConnection getResponseCode)
- 解析 HTTP(HttpURLConnection getResponseCode)
- 解析 HTTP(HttpURLConnection getResponseCode)
- android的socket程序中conn.getResponseCode() 为405
- android开发中conn.getResponseCode()==200抛出异常
- android中onActivityResult不执行
- android的getResponseCode()问题
- android中http访问总结
- HTTP 错误 403.1 - 禁止访问:执行访问被拒绝
- “HTTP 错误 403.1 - 禁止访问:执行访问被拒绝”解决方法
- HTTP 错误 403.1 - 禁止访问:执行访问被拒绝
- 华为P6打开log
- 黑马程序员_交通灯系统代码学习
- js 数字转大写汉字
- 三星手机丢失了数据怎么找回
- 编程规范---如何写出无法维护的代码
- android中Http访问时 connection.getResponseCode()不被执行
- java读取http请求中的body
- 判断SQL数据库是否存在表,是否存在记录
- Java生成二维码
- opencv载入图片,并得到行列值
- Magento 常用技巧与方法
- git恢复删除的分支
- MySQL 模拟条件索引
- SVN不能读取日志