Android 에서 HTTP 를 통 해 날씨 API 가 져 오기(코드 분석)

29353 단어 Android
이 코드 는 수업 자료 로 학습 용 으로 만 사용 되 며 주석 에 분석 되 어 있 습 니 다.
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());
                }
            });
        }
    }
}

HTTP Retrieval.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>

좋은 웹페이지 즐겨찾기