android高级

本文详细介绍了Android高级技术,包括OkHttp的GET和POST异步请求,Retrofit的使用步骤,GreenDao的实体类创建和数据库操作,数据库的升级流程,以及RxJava的基本应用和结合Retrofit进行网络请求。此外,还涉及到了广播、MVP架构模式以及ButterKnife的依赖和插件安装。
摘要由CSDN通过智能技术生成

一、OkHttp

导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.12.0'

get异步:

①创建OKhttpclient对象 new OkHttpClient.Builder().build();

②构建请求对象 new Request.Builder().get().url(url).build();

③获取call对象 okHttpClient.newCall(request);

④call执行请求 call.enqueue(new Callback() {}

private void getEn() {
        //创建okhttpClient 对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new caCheInterCeptor())
                .addNetworkInterceptor(new caCheInterCeptor())
                .cache(new Cache(getCacheDir(), 1024 * 1024 * 60))
                .build();
        //构建请求对象
        Request request = new Request.Builder()
                .url(foodUrl + paramse + page)
                .get()
                .build();
        //获取call对象
        Call call = okHttpClient.newCall(request);
        //call执行请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "网络错误:" + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("TAG", "onResponse当前线程:" + Thread.currentThread().getName());
                String json = response.body().string();
                Log.i("TAG", "json" + json.toString());
                Gson gson = new Gson();
                final FoodBean foodBean = gson.fromJson(json, FoodBean.class);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn_get_en.setText(foodBean.getData().get(5).getTitle());
                    }
                });

            }
        });

post异步:

①创建OKhttpclient 对象new OkHttpClient.Builder().build();

②创建请求体 new FormBody.Builder().add(“stage_id”, “1”).build();

③构建请求对象 new Request.Builder().url(url+from).post(body).build();

④获取call对象 okHttpClient.newCall(request);

⑤call执行请求 call.enqueue(new Callback() {}

private void postEn() {
        //创建 okhttpClient 对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //超时设置
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
               // .addInterceptor(new LogginInterCeptor())//应用拦截器
               // .addNetworkInterceptor(new LogginInterCeptor())//网络拦截器
                //缓存设置
                .cache(new Cache(new File(getCacheDir(), "cache"), 10 * 1024 * 1024))
                .build();
        //创建请求体
        FormBody body = new FormBody.Builder()
                //表单提交
                .add("stage_id", "1")
                .add("limit", "20")
                .add("page", "1")
                .build();
        //创建请求对象
        Request request = new Request.Builder()
                //请求头设置
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                .header("User-Agent", "gaoxiaoqianliutao")
                .url(foodUrl + paramse + page)
                .post(body)
                .build();

        //获取call对象
        Call call = okHttpClient.newCall(request);

        //call执行请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "网络错误:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //响应行
                Log.i("ok", "响应行protocol=" + response.protocol() + "code=" + response.code() + "message=" + response.message());
                //响应头
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    Log.i("ok", headers.name(i) + ":" + headers.value(i));
                }
                //响应体
                String json = response.body().string();
                final FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn_post_en.setText(foodBean.getData().get(5).getTitle());
                    }
                });

            }
        });
    }

请求体
1.form:FormBody.builder().build();

private void postFrom() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        FormBody body = new FormBody.Builder()
                .add("page", "1")
                .add("limit", "20")
                .add("stage_id", "1")
                .build();
        Request request = new Request.Builder()
                .url(foodUrl + parame)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "网络错误:"+e
                .getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                Log.i("TAG", foodBean.getData().get(2).getTitle());
            }
        });
    }

2.string:RequestBody.create(type,"");

private void postString() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        MediaType mediaType = MediaType.parse(formType);
        String content="stage_id=1&limit=20&page=1";
        RequestBody requestBody = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(foodUrl + parame)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "网络错误:"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                Log.i("TAG", foodBean.getData().get(4).getTitle());
            }
        });
    }

3.json

private void postJson() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        FoodJsonBean foodJsonBean = new FoodJsonBean();
        foodJsonBean.setLimit("20");
        foodJsonBean.setPage("1");
        foodJsonBean.setStage_id("1");

        Gson gson = new Gson();
        String json = gson.toJson(foodJsonBean);

        MediaType mediaType = MediaType.parse(jsonType);
        RequestBody requestBody = RequestBody.create(mediaType, json);

        Request request = new Request.Builder()
                .url(foodUrl + parame)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "网络错误:"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                Log.i("TAG", foodBean.getData().get(8).getTitle());
            }
        });
    }

4.stream:new RequestBody()

private void postSteam() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
               return MediaType.parse(formType);
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(steamType);
            }
        };
        Request request = new Request.Builder()
                .url(foodUrl + parame)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "网络错误:"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                Log.i("TAG", foodBean.getData().get(6).getTitle());
            }
        });
    }

5.file

请求头、缓存、超时

请求头:reques.header() request.addHeader()

缓存:okHttpClient.cacha(new Cache(file,time))

超时:ok.timeout()

二、Retrofit

retrofit依赖
implementation 'com.squareup.retrofit2:retrofit:2.5.0'

数据解析器依赖(工厂) (直接可以response.body(),不用new Gson了,非常的方便)

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

retrofit使用步骤

①创建接口服务类:baseURL和方法

②创建retrofit对象 new Retrofit.Builder().baseUrl"(“ApiService.baseUrl”).build();

③通过retrofit对象获取接口服务对象 retrofit.create(ApiService.class);

④接口服务对象调用自己的方法 apiService.get();

⑤通过call执行请求 call.enqueue(new Callback() {}
下面是12种常用注解!!!

每个都要有一个baseUrl呦!!!

 //baseUrl必须以 "/" 结尾
    String baseUrl="http://www.qubaobei.com/ios/cf/";
    @GET("dish_list.php?stage_id=1&limit=20&page=1")
    Call<ResponseBody> get1();

private void get1() {
        //获取retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiServer.baseUrl)
                .build();
        //获取接口服务对象
        ApiServer apiServer = retrofit.create(ApiServer.class);
        //接口服务对象调用接口中的方法得到call对象
        Call<ResponseBody> call = apiServer.get1();
        //call执行请求
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                //当前线程
                Log.i("TAG", "当前线程" + Thread.currentThread().getName());
                try {
                    String json = response.body().string();
                    Log.i("TAG", "responseBody:" + json);
                    FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
                    btn_get1.setText(foodBean.getData().get(3).getTitle());
                    Toast.makeText(MainActivity.this, foodBean.getData().get(5).getTitle(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值