HttpURLConnection+JSON制作天气预报

xml代码如下:

<EditText
    android:gravity="center"
    android:id="@+id/city_et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入城市名" />

<Button
    android:id="@+id/search_btn"
    android:layout_width="150dp"
   android:layout_gravity="center"
    android:layout_height="50dp"
    android:textSize="20sp"
    android:text="查询" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="100dp" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <TextView
            android:id="@+id/tianqi_tv"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="25sp"
            android:text="天气:" />

        <TextView
            android:id="@+id/weather_tv"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:textSize="25sp"
            android:gravity="center"
            android:layout_toRightOf="@+id/tianqi_tv" />
    </RelativeLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <TextView
            android:id="@+id/fengli_tv"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="25sp"
            android:text="风力:" />

        <TextView
            android:id="@+id/wind_tv"
            android:layout_width="wrap_content"
            android:textSize="25sp"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_toRightOf="@+id/fengli_tv" />

    </RelativeLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <TextView
            android:id="@+id/wendu_tv"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="25sp"
            android:text="温度:" />

        <TextView
            android:id="@+id/temp_tv"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:textSize="25sp"
            android:gravity="center"
            android:layout_toRightOf="@+id/wendu_tv" />
    </RelativeLayout>
</LinearLayout>

layout代码如下:

public class WeatherActivity extends AppCompatActivity {
    private TextView weatherTV;
    private TextView windTV;
    private TextView tempTV;
    private Button searchBTN;
    private EditText cityET;
    private String weatherAPI="https://free-api.heweather.com/s6/weather/now?key=8392825b30894374a86421ad2dba3def&location=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        bindID();

        searchBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String city=cityET.getText().toString();
                new MyTask().execute(weatherAPI+city);
            }
        });
    }

    private void bindID() {
        cityET=findViewById(R.id.city_et);
        searchBTN=findViewById(R.id.search_btn);
        weatherTV=findViewById(R.id.weather_tv);
        windTV=findViewById(R.id.wind_tv);
        tempTV=findViewById(R.id.temp_tv);
    }

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


        @Override
        protected String doInBackground(String... strings) {
            StringBuffer stringBuffer=new StringBuffer();
            try{
                URL url=new URL(strings[0]);
                HttpURLConnection connection=(HttpURLConnection)url.openConnection();
                InputStream inputStream=null;
                if(connection.getResponseCode()==200){
                    inputStream=connection.getInputStream();//只有网络正常返回数据正常是,我们才创建输入流
                }else {
                    return "network_failed";
                }

                InputStreamReader reader=new InputStreamReader(inputStream);
                BufferedReader bufferedReader=new BufferedReader(reader);
                String temp="";

                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);
            if (s.equals("network_failed")){
                Toast.makeText(WeatherActivity.this,"网络连接失败",Toast.LENGTH_LONG).show();
            }else {
                //JSON解析
                try{
                    JSONObject object=new JSONObject(s);
                    JSONArray array=object.getJSONArray("HeWeather6");
                    JSONObject object1=array.getJSONObject(0);
                    JSONObject nowObj=object1.getJSONObject("now");
                    String weather=nowObj.getString("cond_txt");
                    String wind=nowObj.getString("wind_dir")+nowObj.getString("wind_sc")+"级";
                    String temperature=nowObj.getString("tmp")+"度";

                    weatherTV.setText(weather);
                    windTV.setText(wind);
                    tempTV.setText(temperature);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
首先绑定ID,声明一个全局的API

定义一个MyTask继承AsyncTask,在DoInBackground方法中实现联网获取数据的耗时操作(可以通过一个if else 判断网络连接是否有用)。在网络连接正常的情况下,接着创建输入流。

在PostExcute方法中利用JSON获取API接口中的数据(注意分清Object还是Array),同样可以判断一下网络连接是否正常。

« »

发表评论

电子邮件地址不会被公开。 必填项已用*标注

昵称 *