OkHttp接入、简单使用、封装

一、接入

先看文档okhttp

接入方式

1-maven

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.11.0</version>
</dependency>

2-gradle

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Android开发一般用这个

3-下载

下载路径:https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=okhttp&v=LATEST
这个不建议

二、使用

请求一般分为get post 两种方式,下面一一说

1.get

// 初始化
OkHttpClient client = new OkHttpClient();

        String url = "";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response result = null;
        try {
        	// 同步
            result = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (result.isSuccessful()) {
            try {
                String string = result.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

}

2.post

// 提交json格式,同步
OkHttpClient client = new OkHttpClient();
        String url = "";

        String content = "";

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("key", "value");
            jsonObject.put("key", "value");
            jsonObject.put("key", "value");
            // ...
        } catch (JSONException e) {
            e.printStackTrace();
        }
        content = jsonObject.toString();

        RequestBody body  = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),content);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
				if (response.isSuccessful()) {
                    String resule = response.body().string();
                }
            }
        });
// 提交表单格式,异步
OkHttpClient client = new OkHttpClient();
        String url = "";
        RequestBody body = new FormBody.Builder().add("key","value").build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

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

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
}

3.下载

 @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                int progress = (int) msg.obj;
                Log.d(TAG, "handleMessage: progress = "+progress);
            }
        }
    };

    private void downLoad() {
        OkHttpClient client = new OkHttpClient();
        String url = "";
        RequestBody body = new FormBody.Builder().add("key","value").build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            
            @Override
            public void onResponse(Call call, Response response){
                if (response.isSuccessful()) {
                    InputStream is = response.body().byteStream();
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                    String name = "downLoadFile.txt";
                    File file = new File(path,name);
                    FileOutputStream fos = null;

                    try {
                        fos = new FileOutputStream(file);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        len = is.read(bytes);
                        int sum = 0;
                        while (len!=-1){
                            fos.write(bytes);
                            sum += len;

                            Message message = handler.obtainMessage(1);
                            message.obj = sum;
                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
    }

三、封装

没有完美的封装,只有适合自己项目的封装,还是自己去GitHub上找吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值