因为公司项目需要使用到天气信息,而且有国外的使用需求,所以就没有选择国内的信息提供商,而是把目光瞄向了国际化的 ACCUWeather。通过下面的两个链接,我们可以简单的了解到AccuWeather的信息和他提供的api。
ACCUWeather简介
ACCU 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 getCityString(@QueryMap Map map);
}
WeatherService.java
public interface WeatherService {
@Headers("Accept-Encoding: application/json")
@GET("currentconditions/v1/{locationKey}")
Call> currentWeather(@Path("locationKey") String locationKey, @QueryMap() Map 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 map = new HashMap<>();
map.put("apikey", APIKEY);
map.put("q", GEOLOCATION);
map.put("language", "en");
NetWork.getInstance()
.getCityService()
.getCityString(map)
.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String key = response.body().getKey();
Log.d(TAG, "onResponse: " + key);
currentWeatherByRetrofit(key);
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
private void currentWeatherByRetrofit(String locationKey) {
String language = "en";
Map map = new HashMap<>();
map.put("apikey", APIKEY);
map.put("language", language);
map.put("details", "true");
NetWork.getInstance()
.getWeatherService()
.currentWeather(locationKey, map)
.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
Log.d(TAG, "onResponse: " + response.body().get(0).toString());
}
@Override
public void onFailure(Call> 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 getCityString(@QueryMap Map map);
}
WeatherApi.java
//定义Weather接口
public interface WeatherApi {
@GET("currentconditions/v1/{locationKey}")
Observable> currentWeather(@Path("locationKey") String locationKey,
@QueryMap() Map map);
}
MainActivity.java
private void findCityByRetrofitRxJava() {
Map 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() {
@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 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>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "currentWeatherByRetrofitRxJava onError: " + e.getMessage());
}
@Override
public void onNext(List lists) {
int size = lists.size();
WeatherBean bean = lists.get(0);
Log.d(TAG, "onNext: " + "size: " + size + "" + bean.toString());
}
});
}
GitHub:代码
本文只是个人工作学习中的知识回顾和记录,如有问题请指出。谢谢。