关于HttpUrlConnection和JSON结合使用的案例(天气预报为例)

1.首先在layout布局文件里定义三个TextView(显示天气,湿度,风向)、一个EdtiView(用来输入城市)和一个Button控件

<EditText
        android:id="@+id/city_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/wind_tx"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <TextView
        android:id="@+id/temp_tx"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <TextView
        android:id="@+id/weather_tx"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <Button
        android:id="@+id/search_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"/>

2.然后就是回到主体类里来定义和绑定这些控件,为Button按钮设置监听

 private EditText cityET;
    private TextView weatherTV;
    private TextView windTV;
    private TextView tempTV;
    private Button searchBtn;
 private void bindID() {
        cityET=findViewById(R.id.city_et);
        weatherTV=findViewById(R.id.weather_tx);
        windTV=findViewById(R.id.wind_tx);
        tempTV=findViewById(R.id.temp_tx);
        searchBtn=findViewById(R.id.search_btn);
    }

3.接着就是定义一个MyTask内部类来继承AsyncTask来实现doInBackground和 onPostExecute方法。首先在doInBackground方法里进行HttpUrlConnection请求的一系列操作

 class MyTask extends AsyncTask<String,Integer,String>{

        @Override
        protected String doInBackground(String... strings) {
            InputStream inputStream=null;
          StringBuffer  stringBuffer =new StringBuffer();
            try {
                URL url=new URL(strings[0]);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();

                if(httpURLConnection.getResponseCode()==200){
                    inputStream=httpURLConnection.getInputStream();
                }else{
                    return "network-failed";
                }

               InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
               BufferedReader bufferedReader=new BufferedReader(inputStreamReader);



                String temp =null;

                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();
        }

注意点:在上面的doInBackground方法里有一个if判断语句,是为了来判断网络返回码是否为200,不是的话就显示“网络异常”


4.在然后就是到onPostExecute方法里了,在里面就是JSON的数据解析操作

   protected void onPostExecute(String s) {
            super.onPostExecute(s);

            try {
                if(s.equals("network-failed")){
                    Toast.makeText(WeatherActivity.this,"网络异常",Toast.LENGTH_SHORT).show();

                }else {
                    JSONObject jsonObject = new JSONObject(s);
                    JSONArray array=jsonObject.getJSONArray("HeWeather6");
                    JSONObject jsonObject1=array.getJSONObject(0);
                    String tmp = jsonObject1.getJSONObject("now").getString("tmp");
                    String wind = jsonObject1.getJSONObject("now").getString("wind_dir") + jsonObject1.getJSONObject("now").getString("wind_sc")+"级";
                    String weather = jsonObject1.getJSONObject("now").getString("cond_txt");
                    weatherTV.setText(weather);
                    windTV.setText(wind);
                    tempTV.setText(tmp);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

注意点:需要注意的是在JSON的数据解析中,每一个JSON数据要和对应的数组相对应,不然则会报错


5.最后就是要在onClick方法里来启动MyTask类了,首先要在全局里先定义一个API,即访问天气的访问网址

private String API="https://free-api.heweather.com/s6/weather/now?key=1318c609832f407dab8f64b44d6d9160&location=";
new  MyTask().execute(API +cityET.getText().toString());

在execute()里不光要放API,要记得把之前定义的输入城市的EditText也一起加进去,不然则会不显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值