网络请求框架 okhttp 简单的使用总结(一)

Android现行的网络请求框架 有很多,我们公司一直用的httpclient,所以空闲时间我想把这些网络请求框架,一一击破。以待以后的项目的优化。

okhttp有很多优点,比如说它支持SPDY,至于SPDY是什么大家自行百度。

它还有一个优点很吸引我,就是它支持缓存管理。这一点对于我们使用httpclient的人来说可真是一大解放。具体如何使用(先给自己埋个坑)后续会带来相关文章。本篇只介绍最简单的用法

入门

官方资料

官方介绍
github源码

使用范围

OkHttp支持Android 2.3及其以上版本。
对于Java, JDK1.7以上。

最简单的使用
初始化:OkHttpClient client = new OkHttpClient();
同步get请求:
private void doGet() {
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();// execute
            if (response.isSuccessful()) {
            String body=response.body().string();
           System.out.println(body);
           String result="doGet|"+response.code()+"|"+body;
                             }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
异步get请求:

private void doGetAsync() {
        Request request = new Request.Builder().url(url).build();
        // enqueue
        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call arg0, IOException arg1) {
            }
            @Override
            public void onResponse(Call arg0, Response response) throws IOException {
                // 不是ui线程
                if (response.isSuccessful()) {
                    System.out.println(response.code());
                   String body=response.body().string();
                    System.out.println(body);
                    String result="doGet|"+response.code()+"|"+body;
                }
            }
        });
    }

post请求上传键值对(也就是上传地址的参数)

    protected void doPost() {
        new Thread(){
            public void run() {
                RequestBody body=new FormBody.Builder()
                 .add("page", "1")
                 .add("code", "news")
                 .add(键, 值)
                 .add(键, 值)
                 .add(键, 值)
                 .build();
                Request  request=new Request.Builder()
                  .url(url)
                  .post(body)
                  .build();
                try {
                    Response response = client.newCall(request).execute();
                    final String string = response.body().string();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            };
        }.start();
    }
post请求上传json字符串

public   static   final   MediaType  JSON  =   MediaType . parse ( "application/json; charset=utf-8" );
String  post ( String  url ,   String  json )   throws   IOException   {
     RequestBody body = RequestBody.create(JSON, json);
      Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
      Response response = client.newCall(request).execute();
    f (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

在此做一个小结
Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。
response.body()返回ResponseBody类该类可以返回字符串(return response.body().string();
字节流(response.body().byteStream();)由此可见okhttp支持大文件下载
文件下载
    public void downLoad() {
        Request request = new Request.Builder().url(
                 url)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call arg0, Response response)
                    throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                String SDPath = Environment.getExternalStorageDirectory()
                        .getAbsolutePath();//下载路径
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(SDPath, "test.3gp");
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        Log.d("h_bl", "progress=" + progress);
                        Message msg = mHandler.obtainMessage();
                        msg.what = 1;
                        msg.arg1 = progress;
                        mHandler.sendMessage(msg);
                    }
                    fos.flush();
                    Log.d("h_bl", "文件下载成功");
                } catch (Exception e) {
                    Log.d("h_bl", "文件下载失败");
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }
        });
    }
Handler mHandler = new Handler() {//更新下载进度

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                int progress = msg.arg1;
                textview.setText(Integer.toString(progress));
                mProgressBar.setProgress(progress);
                break;

            default:
                break;
            }
            super.handleMessage(msg);
        }
    };
文件上传
    private void uploadMultiFile() {
        String path=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.png";//上传文件的地址
        File file=new File(path);
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "test.png", fileBody).build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();

        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = httpBuilder
                // 设置超时
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS).build();
        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call arg0, IOException e) {
                Log.e(TAG, "uploadMultiFile() e=" + e);

            }
            @Override
            public void onResponse(Call arg0, Response response)
                    throws IOException {
                Log.i(TAG, "uploadMultiFile() response="
                        + response.body().string());

            }
        });
    }
以上只是一些基本使用,后续将会带来一些高级的用法。
Demo下载
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值