因為公司項目需要使用到天氣信息,而且有國外的使用需求,所以就沒有選擇國內的信息提供商,而是把目光瞄向了國際化的 ACCUWeather。通過下面的兩個鏈接,我們可以簡單的了解到AccuWeather的信息和他提供的api。
我這里主要使用到兩個訪問URL:
請求城市編碼:
http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=APIKEY&q=GEOLOCATION&language=LANGUAGE
請求當前天氣數據:
http://dataservice.accuweather.com/currentconditions/v1/LOCATIONKEY?apikey=APIKEY&language=LANGUAGE&details=true上面URL中全大寫字母的單詞都是要替換的字符串
APIKEY: 在AccuWeather 開發者網站申請的應用key
GEOLOCATION: 定位獲取到的經緯度數據, 格式是:"經度,緯度"。 由于本文主要是講解天氣API和網絡相關的,所以定位獲取的內容請自行學習。
LANGUAGE:請求想返回的數據的語言。 AccuWeather提供了有限的支持的語言列表,可以自行查詢是否支持你想要的語言。查詢支持的語言
AccuWeather 還有很多其他的如天氣預報等API,需要的可以自行查詢。
下面開始說說Okhttp和Retrofit
Okhttp、Retrofi和RxJava都是目前很盛行的Android開發框架,網絡上面也有很多博客和網站講解了,我這里就不詳細講解原理了,重點是使用。 一言不合就貼代碼。
先使用Okhttp來獲取數據
//構造查詢城市信息的URL
private String findCityByGeoLocation(String geolocation, String lang, boolean withLang) {
StringBuilder builder = new StringBuilder();
builder.append("http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?")
.append("apikey=")
.append(APIKEY)
.append("&q=")
.append(geolocation);
if (withLang) {
builder.append("&language=")
.append(lang);
}
String string = builder.toString();
Log.d(TAG, "findCityByGeoLocation: " + string);
return string;
}
//獲取JsonObject中的key
private int getLocationKey(String response) {
int key = -1;
try {
JSONObject object = new JSONObject(response);
if (object.has("Key")) {
key = object.getInt("Key");
}
} catch (JSONException e) {
e.printStackTrace();
}
return key;
}
//使用Okhttp查詢城市信息
private void findCityByOkHttp() {
OkHttpClient client = new OkHttpClient.Builder().build();
final Request request = new Request.Builder()
.url(findCityByGeoLocation(GEOLOCATION, "en", false))
.build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
String result = response.body().string();
int code = response.code();
Log.d(TAG, "onResponse: " + code + ", " + result);
//使用查詢到的LocationKey 查詢天氣信息
currentWeatherByOkHttp(getLocationKey(result));
}
});
}
//使用Okhttp查詢天氣信息
private void currentWeatherByOkHttp(int locationKey) {
StringBuilder sb = new StringBuilder();
sb.append("http://dataservice.accuweather.com/currentconditions/v1/")
.append(locationKey)
.append("?")
.append("apikey=")
.append(APIKEY)
.append("&")
.append("language=en&")
.append("details=true");
String url = sb.toString();
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
}
上面使用Okhttp的代碼其實很簡單,只有兩步操作,第一,先獲取城市編碼;第二,通過城市編碼獲取天氣數據。使用Okhttp已經如此簡潔了,那使用Retrofit豈不是更爽。
使用Retrofit請求數據
CityService.java
public interface CityService {
@GET("locations/v1/cities/geoposition/search")
Call<CityBean> getCityString(@QueryMap Map<String, String> map);
}
WeatherService.java
public interface WeatherService {
@Headers("Accept-Encoding: application/json")
@GET("currentconditions/v1/{locationKey}")
Call<List<WeatherBean>> currentWeather(@Path("locationKey") String locationKey, @QueryMap() Map<String, String> map);
}
NetWork.java
//定義的方便進行網絡操作的工具類
public class NetWork {
private static final String ACCU_URL = "http://dataservice.accuweather.com/";
private static final int CONNECT_TIME_OUT = 20;
private static final int READ_TIME_OUT = 20;
private static final int WRITE_TIME_OUT = 20;
private static CityApi sCityApi;
private static WeatherApi sWeatherApi;
private static CityService sCityService;
private static WeatherService sWeatherService;
private static OkHttpClient sOkHttpClient;
private static GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create();
private static RxJavaCallAdapterFactory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
private static NetWork sInstance;
private NetWork() {
sOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
.build();
}
public static NetWork getInstance() {
if (sInstance == null) {
synchronized (NetWork.class) {
if (sInstance == null) {
sInstance = new NetWork();
}
}
}
return sInstance;
}
public WeatherApi getWeatherApi() {
if (sWeatherApi == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ACCU_URL)
.client(sOkHttpClient)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
sWeatherApi = retrofit.create(WeatherApi.class);
}
return sWeatherApi;
}
public CityApi getCityApi() {
if (sCityApi == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ACCU_URL)
.client(sOkHttpClient)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
sCityApi = retrofit.create(CityApi.class);
}
return sCityApi;
}
public CityService getCityService() {
if (sCityService == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ACCU_URL)
.client(sOkHttpClient)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
sCityService = retrofit.create(CityService.class);
}
return sCityService;
}
public WeatherService getWeatherService() {
if (sWeatherService == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ACCU_URL)
.client(sOkHttpClient)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
sWeatherService = retrofit.create(WeatherService.class);
}
return sWeatherService;
}
}
MainActivity.java
private void findCityByRetrofit() {
Map<String, String> map = new HashMap<>();
map.put("apikey", APIKEY);
map.put("q", GEOLOCATION);
map.put("language", "en");
NetWork.getInstance()
.getCityService()
.getCityString(map)
.enqueue(new Callback<CityBean>() {
@Override
public void onResponse(Call<CityBean> call, Response<CityBean> response) {
String key = response.body().getKey();
Log.d(TAG, "onResponse: " + key);
currentWeatherByRetrofit(key);
}
@Override
public void onFailure(Call<CityBean> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
private void currentWeatherByRetrofit(String locationKey) {
String language = "en";
Map<String, String> map = new HashMap<>();
map.put("apikey", APIKEY);
map.put("language", language);
map.put("details", "true");
NetWork.getInstance()
.getWeatherService()
.currentWeather(locationKey, map)
.enqueue(new Callback<List<WeatherBean>>() {
@Override
public void onResponse(Call<List<WeatherBean>> call, Response<List<WeatherBean>> response) {
Log.d(TAG, "onResponse: " + response.body().get(0).toString());
}
@Override
public void onFailure(Call<List<WeatherBean>> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
使用了Retrofit之后,我們想RxJava作為目前最火爆的框架之一,能不能加入到我們的項目中呢。
Retrofit + RxJava
CityApi.java
//定義City接口
public interface CityApi {
@GET("locations/v1/cities/geoposition/search")
Observable<CityBean> getCityString(@QueryMap Map<String, String> map);
}
WeatherApi.java
//定義Weather接口
public interface WeatherApi {
@GET("currentconditions/v1/{locationKey}")
Observable<List<WeatherBean>> currentWeather(@Path("locationKey") String locationKey,
@QueryMap() Map<String, String> map);
}
MainActivity.java
private void findCityByRetrofitRxJava() {
Map<String, String> map = new HashMap<>();
map.put("apikey", APIKEY);
map.put("q", GEOLOCATION);
map.put("language", "en");
NetWork.getInstance()
.getCityApi()
.getCityString(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<CityBean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "findCityByRetrofitRxJava onError: " + e.getLocalizedMessage());
}
@Override
public void onNext(CityBean cityBean) {
if (cityBean != null) {
String key = cityBean.getKey();
//to update weather
Log.d(TAG, "onNext: " + cityBean.toString());
currentWeatherByRetrofitRxJava(cityBean);
}
}
});
}
private void currentWeatherByRetrofitRxJava(CityBean cityBean) {
String language = "en";
Map<String, String> map = new HashMap<>();
map.put("apikey", APIKEY);
map.put("language", language);
map.put("details", "false");
NetWork.getInstance()
.getWeatherApi()
.currentWeather(cityBean.getKey(), map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<WeatherBean>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "currentWeatherByRetrofitRxJava onError: " + e.getMessage());
}
@Override
public void onNext(List<WeatherBean> lists) {
int size = lists.size();
WeatherBean bean = lists.get(0);
Log.d(TAG, "onNext: " + "size: " + size + "" + bean.toString());
}
});
}
GitHub:代碼
本文只是個人工作學習中的知識回顧和記錄,如有問題請指出。謝謝。