这是最基础的一个网络服务的一个类,初始化OkHttpClient和Retrofit
public class HttpService {
public static final String BASE_HOST = "http://192.168.0.90:8080/";
private HttpService() {
throw new AssertionError();
}
/**
* 初始化网络通信服务
*/
public static Retrofit init(final Context context) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(cache)
.retryOnConnectionFailure(true)
.connectTimeout(10, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_HOST)
.build();
return retrofit;
}
}
进行网络请求,先构造一个网络请求接口
public interface TestApi {
@Headers({"Content-Type: application/json","charset: utf-8"})
@POST("edu_info/app/BaseApp/updateUser.jspx")
Observable<ResponseBody> getUserInfo(@Body User user);
}
进行网络请求
HttpService.init(context)
.create(TestApi.class)
.getUserInfo(user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull ResponseBody responseBody) {
//成功
}
@Override
public void onError(@NonNull Throwable e) {
//错误处理
}
@Override
public void onComplete() {
}
});
未完
网友评论