okhttp,retrofit,rxjava
2018-05-17 本文已影响0人
霁逸lei
1.OkHttp
enqueue [ɪn'kjuː] (n. 排队;入队;队列)异步调用
execute ['eksɪkjuːt](vt. 实行;执行;处死) 同步调用
看源码知在final class AsyncCall extends NamedRunnable 只有execute方法 来到NamedRunnable
enqueue其实就是在线程run方法中调用execute
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(hongdou)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("MainActivity", e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.d("MainActivity", result);
}
});
2.Retrofit
通过接口获取call对象 然后调用enqueue或者execute
直接通过GsonConverterFactory.create()把得到的String转换成对应的javaBean
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService weatherService = retrofit.create(WeatherService.class);
retrofit2.Call<ResponseWeather> weather = weatherService.getWeather("");
weather.enqueue(new retrofit2.Callback<ResponseWeather>() {
@Override
public void onResponse(retrofit2.Call<ResponseWeather> call, retrofit2.Response<ResponseWeather> response) {
ResponseWeather body = response.body();
Log.d("MainActivity", body.toString());
}
@Override
public void onFailure(retrofit2.Call<ResponseWeather> call, Throwable t) {
Log.d("MainActivity", "onFailure");
}
});
@POST("Langshi/ds/android/weather4")
Call<ResponseWeather> getWeather(@Body String deviceId);
3.rxJava
获取对应的Observable对象然后获取到的数据发送到onNext()
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl1)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
WeatherService service = retrofit.create(WeatherService.class);
service.getWuxiData()
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<WuxiHongdou>() {
@Override
public void accept(WuxiHongdou yinchaun) throws Exception {
Log.d("MainActivity", "yinchaun:" + yinchaun);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.d("MainActivity", "throwable:" + throwable);
}
});