安卓开发--连接到聚合网,获取JSON数据并解析(踩了好多好多坑)

本文将会以从聚合网获得数据为例,介绍如何在Android Studio中获取JSON并解析

这里做一个简单的天气查询的应用

1. 准备工作–导入依赖

JSON解析这里会用到net.sf.json.JSONObject
正常的Android studio会报错,这里需要导入几个jar包
一般情况下,去搜索json-lib-2.4-jdk15.jar就可以找到跟它相关的所有包,如下:
在这里插入图片描述
接下来导入app->libs中
在这里插入图片描述
这里面会有包跟默认的冲突,所以需要手动删除这个文件:
commons-beanutils -> org -> apache -> commons 下的collections文件夹
在这里插入图片描述

2. 核心代码部分

2.1 Get方式的http请求

在开始写代码之前,需要先获取聚合网的API_KEY
在这里插入图片描述

这里与http连接,和JSON解析,都参考了聚合网的查询接口

	// 天气情况查询接口地址
    public static String API_URL = "http://apis.juhe.cn/simpleWeather/query";
    // 接口请求Key,这里需要输入自己的API_KEY
    public static String API_KEY = "xxxxxxxxxxxxxx";

/**
     * get方式的http请求
     *
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    public static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流,并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

2.2 写出查询函数,包含解析

先查询JSON返回示例:

{
    "reason": "查询成功",
    "result": {
        "city": "苏州",
        "realtime": {
            "temperature": "4",
            "humidity": "82",
            "info": "阴",
            "wid": "02",
            "direct": "西北风",
            "power": "3级",
            "aqi": "80"
        },
        "future": [
            {
                "date": "2019-02-22",
                "temperature": "1/7℃",
                "weather": "小雨转多云",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "direct": "北风转西北风"
            },
            {
                "date": "2019-02-23",
                "temperature": "2/11℃",
                "weather": "多云转阴",
                "wid": {
                    "day": "01",
                    "night": "02"
                },
                "direct": "北风转东北风"
            },
            {
                "date": "2019-02-24",
                "temperature": "6/12℃",
                "weather": "多云",
                "wid": {
                    "day": "01",
                    "night": "01"
                },
                "direct": "东北风转北风"
            },
            {
                "date": "2019-02-25",
                "temperature": "5/12℃",
                "weather": "小雨转多云",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "direct": "东北风"
            },
            {
                "date": "2019-02-26",
                "temperature": "5/11℃",
                "weather": "多云转小雨",
                "wid": {
                    "day": "01",
                    "night": "07"
                },
                "direct": "东北风"
            }
        ]
    },
    "error_code": 0
}

JAVA代码:

/**
     * 根据城市名查询天气情况
     *
     * @param cityName
     */
    public static void queryWeather(String cityName) {
        Map<String, Object> params = new HashMap<>();//组合参数
        params.put("city", cityName);
        params.put("key", API_KEY);
        String queryParams = urlencode(params);

        String response = doGet(API_URL, queryParams);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");

                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject realtime = result.getJSONObject("realtime");

				rcvString="";
                rcvString+=("\n城市:"+ result.getString("city"));
                rcvString+=("\n天气:"+ realtime.getString("info"));
                rcvString+=("\n温度:" +realtime.getString("temperature"));
                rcvString+=("\n湿度:"+ realtime.getString("humidity"));
                rcvString+=("\n风向:"+ realtime.getString("direct"));
                rcvString+=("\n风力:"+ realtime.getString("power"));
                rcvString+=("\n空气质量:"+ realtime.getString("aqi"));
            } else {
                Log.d("调用接口失败:" , jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/**
     * 将map型转为请求参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }

2.3 写好显示内容的textView和button

	TextView textView,inputText;
    Button msgBtn;
    public static String rcvString = "";
    textView = findViewById(R.id.textView);
        msgBtn = findViewById(R.id.button);
        inputText = findViewById(R.id.editTextTextPersonName);

        msgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cityName = inputText.getText().toString();
                queryWeather(cityName);
                textView.setText(rcvString);
            }
        });

5. 添加权限

在AndroidManifest.xml文件中添加:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

在这里插入图片描述

android:usesCleartextTraffic="true"

在这里插入图片描述

6. 最后一点小问题

由于传输的数据量可能不小,所以需要在oncreate下面加这么一句话:

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

7. 运行结果

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值