• JSON使用——获取网页返回结果是Json的代码


      public String getWebData(String strUrl){
            String json = null;
            try {
                URL url = new URL(strUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象获取网页数据.
                conn.setConnectTimeout(3 * 1000); // 设置超时时间为3秒
                conn.setRequestMethod("GET");// 可以不设置,默认为GET
                if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
                    InputStream is = conn.getInputStream(); // 获取输入流
                    json = isToString(is); // 把输入流转换转换成字符串
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return json;
        }
    
        
        /**  把输入流转换成字符串   */  
      public String  isToString(InputStream is) throws IOException{ 
            ByteArrayOutputStream baos = new   ByteArrayOutputStream(); 
            int  i=-1; 
            while((i=is.read())!=-1){ 
            baos.write(i); 
            } 
           return baos.toString(); 
    }

    需要注意的是,但凡要联网的:1、都要设置访问权;2、放到线程中去处理

    <uses-permission android:name="android.permission.INTERNET"/>
  • 相关阅读:
    crontab修改默认编辑器
    phpstorm license 解决
    获从2017-2 到现在所有月份;
    获取所在月第一天和最后一天
    EF相关报错
    EF延迟加载LazyLoading
    EF性能优化
    Redis
    搜索服务器Elasticsearch
    Nosql
  • 原文地址:https://www.cnblogs.com/wytings/p/4106719.html
Copyright © 2020-2023  润新知