0315-HttpURLConnection和JASON结合使用(以天气预报为例)

关于本篇博客讲的是HttpURLConnection网络请求与JSON结合使用请求天气预报的例子,

首先,先来了解一下JSON(关于HttpURLConnection详见前三篇博客):
JSON,全称是 JavaScript Object Notation,即 JavaScript 对象标记法。这是一种 轻量级 (Light-Weight)、 基于文本的 (Text-Based)、 可读的 (Human-Readable)格式。
JSON格式有两个显著的优点:书写简单,一目了然;JSON 无论对于人,还是对于机器来说,都是十分便于阅读和书写的,而且相比 XML 文件更小;JSON 格式的创始人声称此格式永远不升级,这就表示这种格式具有长时间的稳定性;

1.JSON对值的类型和格式有严格的规定

复合类型的值只能是数组或对象,不能是函数、正则表达式对象、日期对象。
简单类型的值只有四种:字符串、数值(必须以十进制表示)、布尔值和null(不能使用NaN, Infinity, -Infinity和undefined)。
字符串必须使用双引号表示,不能使用单引号。
对象的键名必须放在双引号里面。
数组或对象最后一个成员的后面,不能加逗号。

PS: 需要注意的是,空数组和空对象都是合格的JSON值,null本身也是一个合格的JSON值。

2.JSON 的语法规则

JSON 的语法规则十分简单,可称得上“优雅完美”,总结起来有:
数组(Array)用方括号(“[]”)表示。
对象(Object)用大括号(”{}”)表示。
名称/值对(name/value)组合成数组和对象。
名称(name)置于双引号中,值(value)有字符串、数值、布尔值、null、对象和数组。
并列的数据之间用逗号(“,”)分隔。

接下来请看天气预报实例:

效果图:

这里写图片描述

1.首先,创建Activity,布置其xml代码:
<?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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.test.project.jsondate.Weather1Activity">

    <EditText
        android:id="@+id/city_et"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="请输入城市"
        />
    <Button
        android:id="@+id/search_Btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="20sp"
        android:text="搜索"
        />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:id="@+id/tv1"
            android:text="温度:"

            />
        <TextView
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:id="@+id/tv2"
            android:layout_below="@+id/tv1"
            android:text="天气:"

            />
        <TextView
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:id="@+id/tv3"
            android:layout_below="@+id/tv2"
            android:text="风力:"

            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/wendu_tv"
            android:textSize="20sp"
            android:layout_toRightOf="@+id/tv1"

            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/weather_tv"
            android:textSize="20sp"
            android:layout_toRightOf="@+id/tv2"
            android:layout_below="@+id/tv1"

            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/wind_tv"
            android:textSize="20sp"
            android:layout_toRightOf="@+id/tv3"
            android:layout_below="@+id/tv2"

            />
    </RelativeLayout>



</LinearLayout>
Java代码:
package com.test.project.jsondate;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Weather1Activity extends AppCompatActivity {

    private EditText cityET;
    private Button button;
    private TextView windtv;
    private TextView wendutv;
    private TextView weathertv;
    //天气预报接口
    private  String API="https://free-api.heweather.com/s6/weather/now?key=389b98d2fe6e402483428f6510250c3d&location=";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather1);
        bindId();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String city=cityET.getText().toString();
                //启动Mytask
                new Mytask().execute(API+city);

            }
        });
    }

    class  Mytask extends AsyncTask<String,Integer,String>{
        @Override
        protected String doInBackground(String... strings) {
            //定义StringBuffur对象
            StringBuffer stringBuffer=null;
            try {
                //定义URL对象
                URL  url=new URL(strings[0]);
                //调用URL对象获得openConnection方法
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                //获取输入流
                InputStream inputStream=httpURLConnection.getInputStream();
                InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
                //读取输入流
                BufferedReader bufferedReader=new BufferedReader(reader);
                stringBuffer=new StringBuffer();

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

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stringBuffer.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try{
                //通过JSONObject方法获得JSONObject对象(键名)
                JSONObject object=new JSONObject(s);
                //通过键名获得对应数组对象
                JSONObject obj=object.getJSONArray("HeWeather6").getJSONObject(0);
                //获得所需键名
              String temp=obj.getJSONObject("now").getString("tmp");
              String  wind=obj.getJSONObject("now").getString("wind_dir")+obj.getJSONObject("now").getString("wind_sc")+"级";
                String weather=obj.getJSONObject("now").getString("cond_txt");
                //将JASON数值传入对应控件中
                weathertv.setText(weather);
                windtv.setText(wind);
                wendutv.setText(temp);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    private void bindId() {
        cityET=findViewById(R.id.city_et);
        button=findViewById(R.id.search_Btn);
        windtv=findViewById(R.id.wind_tv);
        wendutv=findViewById(R.id.wendu_tv);
        weathertv=findViewById(R.id.weather_tv);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值