• Android: HttpURLConnection获取JSON数据


    public class GetJsonDataTask extends AsyncTask {
        private TextView tv;
    
        public GetJsonDataTask(TextView tv) {
            super();
            this.tv = tv;
        }
        /**
         * 这里的String参数对应AsyncTask中的第一个参数   
         * 这里的String返回值对应AsyncTask的第三个参数  
         * 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改  
         * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作  
         */
        @Override
        protected String doInBackground(String... urls) {
            try {
                URL url = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                String resp_content = "";
                int code = conn.getResponseCode();
                if (code == 200) {
                    InputStream is = conn.getInputStream();
                    resp_content = readInputStreamToString(is);
                }
                return resp_content;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)
         * 在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI控件进行设置
         */
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tv.setText(s);
        }
    
        //字节流转换成字符串
        private static String readInputStreamToString(InputStream is) {
            byte[] result;
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                is.close();
                baos.close();
                result = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                return "获取数据失败";
            }
            return new String(result);
        }
    }
  • 相关阅读:
    多参加活动,生活才精彩
    vue 使用 创建二维数组响应数据 渲染 echarts图标
    FPGA之旅设计第五例-----IIC通信
    父子项目打包发布至私仓库
    git提交代码到远程仓库
    安全项目简介
    cookie介绍:cookie实现增删改查功能
    速卖通店铺流量下滑什么原因,如何做提升?(测评补单)
    ArcGIS pro 支持 发布三维服务
    19. 从零开始编写一个类nginx工具, 配置数据的热更新原理及实现
  • 原文地址:https://blog.csdn.net/liuliuhelingdao/article/details/125401948