安卓Http请求(三)

1.以天气预报为实例
这次HTTP请求是与json联合使用,这里先介绍一下json,json是一个轻量级数据交换格式。
下面将系统的讲一下json
2.json
json数据又三种,单条、数组、嵌套这三种。其中比较重要的是json数据解析。
其中要利用工具解析json数据比较好用但是json.com
使用json效果如下
这里写图片描述

单条json数据解析

            //json数据
            private String jsonStr = "{\"name\":\"张三\",\"age\":21}";
            //单条Json解析
            JSONObject jsonObject=new JSONObject(jsonStr);
            String name=jsonObject.getString("name");
            int age=jsonObject.getInt("age");
            Log.e("main",name+age);//打印日志

嵌套json数据解析

//json数据
 private String jsonStr2 = "{\"name\":\"张三\",\"age\":21,\"info\":{\"class \":\"软件164\",\"id\":1617133101}}";
  //嵌套的单条Json解析
          JSONObject jsonObject = new JSONObject(jsonStr2);
           String name = jsonObject.getString("name");
           int age = jsonObject.getInt("age");
           JSONObject info = jsonObject.getJSONObject("info");
           String classname = info.getString("class");
           int id = info.getInt("id");
           Log.e("Json", name + age + classname + id);

3.天气预报实例
首先设计ui界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.example.ll.skt.WeatherActivity">
<EditText
    android:id="@+id/edic"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入城市名"/>
    <Button
        android:text="查询"
        android:id="@+id/btnic"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:textSize="20dp"
            android:id="@+id/tianqi"
            android:text="天气:"
            android:layout_width="match_parent"
            android:layout_height="50dp" />
        <TextView
            android:textSize="20dp"
            android:id="@+id/wendu"
            android:text="温度:"
            android:layout_width="match_parent"
            android:layout_height="50dp" />
        <TextView
            android:textSize="20dp"
            android:id="@+id/fengli"
            android:text="风向:"
            android:layout_width="match_parent"
            android:layout_height="50dp" />
    </LinearLayout>

</LinearLayout>

然后绑定Id

  private void BindId() {
        editText = findViewById(R.id.edic);
        btn = findViewById(R.id.btnic);
        tv1 = findViewById(R.id.tianqi);
        tv2 = findViewById(R.id.wendu);
        tv3 = findViewById(R.id.fengli);
    }

接着获取json数据

    private String weatherApI = "https://free-api.heweather.com/s6/weather/now?key=1153ea9909df4ec0b9145e88f9de4632&location=";

创建内部类继承AsyncTask方法

 protected String doInBackground(String... strings) {
            StringBuffer stringBuffer = new StringBuffer();
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = null;
                if (httpURLConnection.getResponseCode() == 200) {
                //只有网络正常时返回数组正常,才能创建输入流
                    inputStream = httpURLConnection.getInputStream();                } else {
                    return "Network_failed";//网络连接失败
                }
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                String temp = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    stringBuffer.append(temp);
                }

                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return stringBuffer.toString();
        }

解析json数据

protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("Network_failed")) {
                Toast.makeText(WeatherActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            } else {
                //Json解析
                try {
                    JSONObject object = new JSONObject(s);
                    JSONArray array = object.getJSONArray("HeWeather6");
                    JSONObject object1 = array.getJSONObject(0);
                    JSONObject now = object1.getJSONObject("now");
                    String wether = now.getString("cond_txt");
                    String wind = now.getString("wind_dir") + now.getString("wind_sc") + "级";
                    String wendu = now.getString("tmp");
                    //赋值
                    tv1.setText(wether);
                    tv2.setText(wendu);
                    tv3.setText(wind);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

完成效果如下
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值