有很多方式
实现我介绍Rxjava 加上Okhttp的请求方式
首先我们需要导入依赖
compile 'io.reactivex:rxjava:1.0.10'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.okhttp3:okhttp:3.3.0'
这里我们使用的十Rxjava 1的版本
写入一个布局文件
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/title"
android:textSize="20sp"
android:text="我的标题"/>
</LinearLayout>
有了标题了我们就要获取空间Id和使用网络请求数据的Bean对象的类
这里我就不导入Bean类了
只要记住Bean 对象就是Bean类就可以’
下面就是我们在使用 Rxjava 的使用 的观察者 和 被观察者的使用
观察者实在主线程执行 被观察者在子线程执行
观察者是做就是被观察者发来的数据 被观察者是使用的Okhttp 请求的网络数据
下面就是代码的实现
这里是观察者
Observer<Bean> observer = new Observer<Bean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "请求HTTP失败!", Toast.LENGTH_LONG).show();
}
@Override
public void onNext(Bean bean) {
Toast.makeText(MainActivity.this, "请求HTTP成功!", Toast.LENGTH_LONG).show();
title.setText(bean.getData().getTitle());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (TextView) findViewById(R.id.title);
//被观察
Observable.OnSubscribe<Bean> observable = new Observable.OnSubscribe<Bean>(){
@Override
public void call(final Subscriber<? super Bean> subscriber) {
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url("http://169.254.247.113:8080/WebSample/action/book_detail?id=5").build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
subscriber.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String s = response.body().string();
Bean bean = new Gson().fromJson(s,Bean.class);
subscriber.onNext(bean);
}
});
}
};
Observable.create(observable).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(observer);
}
简单实现的