okhttp网络请求框架

* okhttp是非常高效的网络请求,它是基于http/http2* <p/>
* 1、允许同一主机的所有请求共享一个socket
* 2、减少网络请求时间Connection pooling reduces request latency (if HTTP/2 isn’t available).
* 3、使用gzip压缩,缩小下载大小。
* 4、响应缓存避免了网络重复请求
* 5、断线重连,多地址请求备用。

* 6、使用简单,支持同步和异步请求。

GET请求:

  private void initHttp() {
        //创建Request请求对象,默认为get请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        //获得Call(调度)接口对象
        Call call = mokHttpClient.newCall(request);

        //把请求加入调度
        call.enqueue(new Callback() {
            @Override//失败的回调方法
            public void onFailure(Call call, IOException e) {

            }

            @Override//成功的回调方法
            public void onResponse(Call call, Response response) throws IOException {

                String str = response.body().string();//该方法只能使用一次

                System.out.println(str);
                System.out.println("-------------------当前线程的id为:" + Thread.currentThread().getId());
            }
        });
    }




POST请求:

异步任务执行:

private int page = 0;//接口的请求参数(post请求)
private void httpPost() {//post请求
    page++;
    //健康知识列表接口-天狗健康知识分类列表API接口,post请求的参数
    //创建FormBody.Builder对象
    FormBody.Builder fb = new FormBody.Builder();
    fb.add("page", page + "");//设置请求的参数
    fb.add("rows", page * 5 + "");//添加请求的参数

    //新建一个请求对象
    final Request request = new Request.Builder()
            .url("http://www.tngou.net/api/lore/list")
            .post(fb.build())//请求方式(post请求)
            .build();//构造对象

    //异步方法访问网络
    mokHttpClient.newCall(request).enqueue(
            new Callback() {
                @Override//访问失败会调用该方法
                public void onFailure(Call call, IOException e) {

                }

                @Override//访问成功调用
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    System.out.println("==============" + str);
                    System.out.println("-------------------当前线程的id为:" + Thread.currentThread().getId());
                }
            }
    );

同步任务执行:
//OkHttpClient框架同步访问网络(会在主线程访问,需要开启子线程)
try {
    new Thread(){
        @Override
        public void run() {//子线程
            try {
                //同步方法访问网络
                Response response=mokHttpClient.newCall(request).execute();
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();//开启线程

} catch (Exception e) {
    e.printStackTrace();
}




POST请求,上传文件
    private void uploadPost() {//post请求,上传文件到服务器
        //要上传文件的路径
        final String filepath = Environment.getExternalStorageDirectory() + "/aa.jpg";
        String url = "http://192.168.58.1:8080/file/upload";

        MultipartBody.Builder mrb = new MultipartBody.Builder();

        File file = new File(filepath);
        RequestBody rb = RequestBody.create(MediaType.parse(""), file);
        mrb.setType(MultipartBody.FORM);//文件上传必须设置

        mrb.addFormDataPart(
                "file",//form表单里面的值
                "hhhh",//服务器上保存的名字
                rb//文件内容
        );

        Request request=new Request.Builder()
                .url(url)
                .post(mrb.build())
                .build();

        mokHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json=response.body().string();

                try {
                    JSONObject jsonObject=new JSONObject(json);
                    String error=jsonObject.optString("error");

                    if(TextUtils.isEmpty(error)){
                        return;
                    }

                    if(error.equals("0")){
                        Log.i("MainActivity","----上传文件成功!");
                    }else{
                        Log.i("MainActivity","-----文件上传失败 !");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                        Log.i("MainActivity","-----文件上传失败 !");
                }
            }
        });



GET请求,下载网络图片
<pre name="code" class="java">  private int sum = 0;//记录文件的字节长度
    private void doenPost() {//get请求,下载网络文件
        String url = "https://img3.doubanio.com/view/photo/photo/public/p1787067956.jpg";
        final String filepath = Environment.getExternalStorageDirectory() + "/aa.jpg";
        System.out.println("---------文件的保存路径为:" + filepath);
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();


        mokHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("-------------------当前线程的id为:" + Thread.currentThread().getId());
                InputStream is = response.body().byteStream();//获得输入流

                final Bitmap bitmap = BitmapFactory.decodeStream(is);


<span style="white-space:pre">		</span>runOnUiThread(new Runnable() { //主线程运行该run方法
   <span style="white-space:pre">			</span> @Override
   <span style="white-space:pre">		</span> public void run() {
        System.out.println("=========================runOnUiThread的run方法中,当前线程的id为:" + Thread.currentThread().getId());
        System.out.println("=========================runOnUiThread的run方法中,Bitmap为:" + bitmap);

        image.setImageBitmap(bitmap);
    }
});




                
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值