Android 下通过 HTTP 获取天气 API(代码分析)

本代码为课堂教学材料,仅作学习使用,分析在注释里面。

MainActivity.java

import com.example.http.HTTPRetrieval;
import com.example.http.JSONParser;
import com.example.http.WeatherInfo;

public class MainActivity extends AppCompatActivity {

    private TextView txt;

    private Handler hd;

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

        txt = (TextView) findViewById(R.id.textView1);

        hd = new Handler();
// 启用网络线程
        HttpThread ht = new HttpThread();
        ht.start();

    }

    public class HttpThread extends Thread {
        @Override
        public void run() {
            super.run();
            HTTPRetrieval hr = new HTTPRetrieval();
            // 城市代码
            String weatherString = hr.HTTPWeatherGET("101270101");

            WeatherInfo wi = new WeatherInfo();
            JSONParser jp = new JSONParser();
            // 调用自定义的 JSON 解析类解析获取的 JSON 数据
            wi = jp.WeatherParse(weatherString);

            final WeatherInfo finalWi = wi;
            // 多线程更新 UI
            hd.post(new Runnable() {
                @Override
                public void run() {
                    txt.setText(finalWi.getCity() + finalWi.getHighTemp() + finalWi.getLowTemp() + finalWi.getDescription() + finalWi.getPublishTime());
                }
            });
        }
    }
}

HTTPRetrieval.java(用于处理 HTTP)

package com.example.http;

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

public class HTTPRetrieval {
    public String HTTPWeatherGET(String cityCode) {
        String res = "";
        // StringBuilder 的作用类似于 + ,用于将字符串连接在一起
        StringBuilder sb = new StringBuilder();
        String urlString = "http://www.weather.com.cn/adat/cityinfo/" + cityCode + ".html";
        try {
        // URL 是对 url 的处理类
            URL url = new URL(urlString);
       	// 得到connection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(10000);
          	// 使用 InputStreamReader 进行数据接收
            InputStreamReader isr = new InputStreamReader(httpURLConnection.getInputStream());
            // 缓存
            BufferedReader br = new BufferedReader(isr);
            String temp = null;
			// 读取接收的数据
            while ( (temp = br.readLine()) != null) {
                sb.append(temp);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        res = sb.toString();
        return res;
    }
}

JSONParser.java(用于解析 JSON 数据)

package com.example.http;

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

public class JSONParser {
    public WeatherInfo WeatherParse (String weatherString) {
        WeatherInfo wi = new WeatherInfo();
        try {
            JSONObject jo = new JSONObject(weatherString);
            JSONObject joWeather = jo.getJSONObject("weatherinfo");
            wi.setCity(joWeather.getString("city"));
            wi.setLowTemp(joWeather.getString("temp2"));
            wi.setHighTemp(joWeather.getString("temp1"));
            wi.setDescription(joWeather.getString("weather"));
            wi.setPublishTime(joWeather.getString("ptime"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return wi;
    }
}

WeatherInfo.java(

package com.example.http;

public class WeatherInfo {
// 数据接收
    private String city;
    private String description;
    private String highTemp;
    private String lowTemp;
    private String publishTime;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getHighTemp() {
        return highTemp;
    }

    public void setHighTemp(String highTemp) {
        this.highTemp = highTemp;
    }

    public String getLowTemp() {
        return lowTemp;
    }

    public void setLowTemp(String lowTemp) {
        this.lowTemp = lowTemp;
    }

    public String getPublishTime() {
        return publishTime;
    }

    public void setPublishTime(String publishTime) {
        this.publishTime = publishTime;
    }


}

AndroidManifest.xml(在该配置文件中打开网络权限)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.examplehttp">
// 启用网络权限
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

你可能感兴趣的:(Android)