OkHttp使用总结

一 OkHttp介绍

OkHttp是一个优秀的网络请求框架,目前主流已经替换httpclient, HttpURLConnection 使用方式;

OkHttp支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,自带GZIP压缩,请求缓存等优势;

OkHttp 成为 Android 最常见的网络请求库, 但并不妨碍java后端学习他,所以这边知识追寻者 做了常用总结

github: https://github.com/square/okhttp

官方文档:https://square.github.io/okhttp/

二 依赖

目前最新版本:4.9.0

maven

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

gradle

compile 'com.squareup.okhttp3:okhttp:3.6.0'

三 GET 请求

请求步骤

  1. 获取OkHttpClient对象
  2. 设置请求request
  3. 封装call
  4. 异步调用,并设置回调函数
 /**
     * @Author lsc
     * <p>get 请求 </p>
     * @Param [url]
     * @Return
     */
    public void get(String url){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2设置请求
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        // 3封装call
        Call call = client.newCall(request);
        // 4异步调用,并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                    // response.body().string();
                }
            }
        });
        //同步调用,返回Response,会抛出IO异常
        //Response response = call.execute();
    }

四 POST 请求

4.1 form 表单形式

  1. 获取OkHttpClient对象
  2. 构建参数body
  3. 构建 request
  4. 将Request封装为Call
  5. 异步调用
 /**
     * @Author lsc
     * <p> post 请求, form 参数</p>
     * @Param [url]
     * @Return
     */
    public void postFormData(String url){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2 构建参数
        FormBody formBody = new FormBody.Builder()
                .add("username", "admin")
                .add("password", "admin")
                .build();
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        // 4 将Request封装为Call
        Call call = client.newCall(request);
        // 5 异步调用
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                }
            }
        });
    }

4.2 json参数形式

  1. 获取OkHttpClient对象
  2. 构建参数
  3. 构建 request
  4. 将Request封装为Call
  5. 异步调用
/**
     * @Author lsc
     * <p>post 请求 ,json参数 </p>
     * @Param [url, json]
     * @Return
     */
    public void postForJson(String url, String json){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2 构建参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        // 4 将Request封装为Call
        Call call = client.newCall(request);
        // 5 异步调用
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                }
            }
        });
    }

如果是json字符串,替换请求媒体类型即可

 // 2 构建参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}");
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

4.3 文件下载

  1. 获取OkHttpClient对象
  2. 构建 request
  3. 异步调用
  4. 文件下载
/**
     * @Author lsc
     * <p> 文件下载 </p>
     * @Param url 下载地址url
     * @Param target 下载目录
     * @Param target 文件名
     * @Return
     */
    private void download(String url, String target, String fileName){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2构建 request
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 3 异步调用
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    // 4 文件下载
                    downlodefile(response, target,fileName);
                }
            }
        });
    }

    private void downlodefile(Response response, String url, String fileName) {
        InputStream inputStream = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream outputStream = null;
        try {
            inputStream = response.body().byteStream();
            //文件大小
            long total = response.body().contentLength();
            File file = new File(url, fileName);
            outputStream = new FileOutputStream(file);
            long sum = 0;
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

4.4 文件上传

  1. 获取OkHttpClient对象
  2. 封装参数以 form形式, 媒体格式为二进制流
  3. 封装 request
  4. 异步回调
/**
     * @Author lsc
     * <p> 文件上传 </p>
     * @Param [url]
     * @Return
     */
    public void upload(String url){
        File file = new File("C:/mydata/generator/test.txt");
        if (!file.exists()){
            System.out.println("文件不存在");
        }else{
            // 获取OkHttpClient对象
            OkHttpClient client = new OkHttpClient();
            // 2封装参数以 form形式
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("username", "admin")
                    .addFormDataPart("password", "admin")
                    .addFormDataPart("file", "555.txt", RequestBody.create(MediaType.parse("application/octet-stream"), file))
                    .build();
            // 3 封装 request
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            // 4 异步回调
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

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

                }
            });
        }
    }

公众号知识追寻者,欢迎关注,获取原创PDF,面试题集

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用OkHttp3实现WebSocket的步骤如下: 首先,我们需要导入OkHttp的依赖库。可以通过在项目的build.gradle文件的dependencies块中添加以下代码来实现: implementation 'com.squareup.okhttp3:okhttp:3.14.0' 接下来,我们在代码中创建一个OkHttpClient实例,并使用它来建立WebSocket连接。例如: OkHttpClient client = new OkHttpClient(); // WebSocket连接地址 String url = "ws://example.com/socket"; // 创建WebSocket请求 Request request = new Request.Builder().url(url).build(); // 建立WebSocket连接 WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { super.onOpen(webSocket, response); // 连接已经建立 Log.d("WebSocket", "连接已经建立"); } @Override public void onMessage(WebSocket webSocket, String text) { super.onMessage(webSocket, text); // 接收到消息 Log.d("WebSocket", "接收到消息:" + text); } @Override public void onClosed(WebSocket webSocket, int code, String reason) { super.onClosed(webSocket, code, reason); // 连接已关闭 Log.d("WebSocket", "连接已关闭"); } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { super.onFailure(webSocket, t, response); // 连接失败 Log.d("WebSocket", "连接失败"); } }); 通过上述代码,我们使用OkHttpClient创建了一个WebSocket连接,建立连接时会调用onOpen方法,接收到消息时会调用onMessage方法,连接关闭时会调用onClosed方法,连接失败时会调用onFailure方法。 我们还可以通过WebSocket对象发送消息,例如: webSocket.send("Hello, WebSocket!"); 当我们不再需要WebSocket连接时,可以通过调用webSocket.close()方法来关闭连接。 总结来说,使用OkHttp3实现WebSocket非常方便,只需要创建OkHttpClient对象,根据WebSocket的生命周期处理不同的回调方法即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值