总体框架
通过OkHttpClient与对应网址建立连接,并从网址中获得Json字符串数据,利用Gson解析数据获得各类信息。
模块一、建立连接
目
的
:
与
网
址
进
行
连
接
并
获
取
数
据
目的:与网址进行连接并获取数据
目的:与网址进行连接并获取数据
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址,设置请求方式。
Request request = new Request.Builder().url("http://www.weather.com.cn/data/sk/101280101.html").method("GET",null).build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.请求加入调度,重写回调方法
call.enqueue(new Callback() {
//请求失败执行的方法
@Override
public void onFailure(Call call, IOException e) {
}
//请求成功执行的方法
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
模块二、解析数据,分析数据格式
final String in = response.body().string();//解析数据,转换成字符串类型
解 析 字 符 串 结 果 如 下 : 解析字符串结果如下: 解析字符串结果如下:
{"weatherinfo":{"city":"广州","cityid":"101280101","temp":"26.6","WD":"东南风","WS":"小于3级","SD":"83%","AP":"1001.4hPa","njd":"暂无实况","WSE":"<3","time":"17:50","sm":"1.7","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}
利 用 数 据 格 式 , 通 过 G s o n F o r m a t 生 成 类 代 码 利用数据格式,通过GsonFormat生成类代码 利用数据格式,通过GsonFormat生成类代码
public class Weather {
private WeatherinfoBean weatherinfo;
public static class WeatherinfoBean {
private String city;
private String cityid;
private String temp;
@SerializedName("WD")
private String wD;
@SerializedName("WS")
private String wS;
@SerializedName("SD")
private String sD;
@SerializedName("AP")
private String aP;
private String njd;
@SerializedName("WSE")
private String wSE;
private String time;
private String sm;
private String isRadar;
@SerializedName("Radar")
private String radar;
//Getter and Setter代码生成
}
//Getter and Setter代码生成
}
模块三、非主线程对主线程的访问
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
weather = gson.fromJson(in, Weather.class);
setWeatherDat();
}
});
模块四、setWeatherDat()显示信息函数构造
private void setWeatherDat(){
city.setText(weather.getWeatherinfo().getCity());
time.setText(weather.getWeatherinfo().getTime());
direction.setText("风向:"+weather.getWeatherinfo().getwD());
level.setText("风级:"+weather.getWeatherinfo().getwS());
temp.setText("温度:"+weather.getWeatherinfo().getTemp());
}