其他分享
首页 > 其他分享> > Retrofit网络

Retrofit网络

作者:互联网

public class HttpUtils {

public boolean isnet(Context context){
    if (context!=null) {
        ConnectivityManager systemService =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = systemService.getActiveNetworkInfo();
        if (activeNetworkInfo!=null){
            return activeNetworkInfo.isConnected();
        }
    }
    return false;
}

private String baseUr="http://172.17.8.100";
//传递头参
private Map<String,String> headMap = new HashMap<>();
public HttpUtils setHead(Map<String,String > headMap){
    this.headMap=headMap;
    return this;
}
//get请求
public HttpUtils get(String url, Map<String,String> map) {
    if (map==null){
        map=new HashMap<>();
    }
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            return chain.proceed(request);
        }
    }).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUr)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(client)
            .build();
    HttpService service = retrofit.create(HttpService.class);
    service.get(url,headMap,map)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<ResponseBody>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(ResponseBody responseBody) {
                    try {
                        String data = responseBody.string();
                        HttpUtils.this.httpListner.success(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void one rror(Throwable e) {
                   String message = e.getMessage();
                   HttpUtils.this.httpListner.error(message);
                }

                @Override
                public void onComplete() {

                }
            });
    return this;
}
private HttpListner httpListner;
public void result(HttpListner httpListner){
    this.httpListner=httpListner;
}

}

标签:headMap,HttpUtils,void,httpListner,网络,Retrofit,new,public
来源: https://blog.csdn.net/chenxchhh/article/details/89438042