okhttp的使用

简介: okhttp的使用

1.导入依赖

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

2.申请权限

<uses-permission android:name="android.permission.INTERNET"/>

android10 以上要在manifest下声明 :android:usesCleartextTraffic="true"

3.get请求

   public void getRq(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().get().url("http://www.baidu.com/").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,e.toString());
            }
 
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)
                    throws IOException {
                Log.e(TAG,response.body().string());
            }
        });
    }

4.post请求

    public void postQQ(){
        OkHttpClient okHttpClient = new OkHttpClient();
        //提交键值对
        FormBody formBody = new FormBody.Builder().
                add("username","2545993152@qq.com").
                add("password","eandhhds").
                build();
        //提交字符串
 
        JSONObject jsonObject  = new JSONObject();
        try {
            jsonObject.put("name","dddd");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}");
        //上传文件
        File file = new File(Environment.getExternalStorageDirectory(), "1.png");
        if (!file.exists()){
            Log.e(TAG,"文件不存在");
        }else{
            RequestBody requestBody2 = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        }
        Request request = new Request.Builder().url("http://www.jianshu.com/")
                .post(formBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,e.toString());
            }
 
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)
                    throws IOException {
                Log.e(TAG,response.body().string());
            }
        });
    }

5.复杂表单

   public void postMultiForm(){
 
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "admin")//
                .addFormDataPart("password", "admin")//
                .addFormDataPart("myfile", "1.png",     RequestBody.create(MediaType.parse("application/octet-stream"), file));
    }

6.下载文件

导入依赖:

implementation 'com.squareup.okio:okio:2.8.0'

    public void downloadImg(View view){
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url("https://www.baidu.com/img/bd_logo1.png")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("moer", "onFailure: ");;
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //拿到字节流
                InputStream is = response.body().byteStream();
 
                int len = 0;
                File file  = new File(Environment.getExternalStorageDirectory(), "n.png");
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[128];
 
                while ((len = is.read(buf)) != -1){
                    fos.write(buf, 0, len);
                }
 
                fos.flush();
                //关闭流
                fos.close();
                is.close();
            }
        });
    }

下载的图片设置到 imageview

@Override
public void onResponse(Call call, Response response) throws IOException {
    InputStream is = response.body().byteStream();
 
    final Bitmap bitmap = BitmapFactory.decodeStream(is);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            imageView.setImageBitmap(bitmap);
        }
    });
 
    is.close();
}

7.增加 进度条:

下载:

@Override
public void onResponse(Call call, Response response) throws IOException {
    InputStream is = response.body().byteStream();
    long sum = 0L;
    //文件总大小
    final long total = response.body().contentLength();
    int len = 0;
    File file  = new File(Environment.getExternalStorageDirectory(), "n.png");
    FileOutputStream fos = new FileOutputStream(file);
    byte[] buf = new byte[128];
 
    while ((len = is.read(buf)) != -1){
        fos.write(buf, 0, len);
        //每次递增
        sum += len;
 
        final long finalSum = sum;
        Log.d("pyh1", "onResponse: " + finalSum + "/" + total);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //将进度设置到TextView中
                contentTv.setText(finalSum + "/" + total);
            }
        });
    }
    fos.flush();
    fos.close();
    is.close();
}

上传:

自定义类继承RequestBody,然后重写其中的方法,将其中的上传进度通过接口回调暴露出来供我们使用。

public class CountingRequestBody extends RequestBody {
    //实际起作用的RequestBody
    private RequestBody delegate;
    //回调监听
    private Listener listener;
 
    private CountingSink countingSink;
 
    /**
     * 构造函数初始化成员变量
     * @param delegate
     * @param listener
     */
    public CountingRequestBody(RequestBody delegate, Listener listener){
        this.delegate = delegate;
        this.listener = listener;
    }
    @Override
    public MediaType contentType() {
        return delegate.contentType();
    }
 
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        countingSink = new CountingSink(sink);
        //将CountingSink转化为BufferedSink供writeTo()使用
        BufferedSink bufferedSink = Okio.buffer(countingSink);
        delegate.writeTo(bufferedSink);
        bufferedSink.flush();
    }
 
    protected final class CountingSink extends ForwardingSink{
        private long byteWritten;
        public CountingSink(Sink delegate) {
            super(delegate);
        }
 
        /**
         * 上传时调用该方法,在其中调用回调函数将上传进度暴露出去,该方法提供了缓冲区的自己大小
         * @param source
         * @param byteCount
         * @throws IOException
         */
        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            byteWritten += byteCount;
            listener.onRequestProgress(byteWritten, contentLength());
        }
    }
 
    /**
     * 返回文件总的字节大小
     * 如果文件大小获取失败则返回-1
     * @return
     */
    @Override
    public long contentLength(){
        try {
            return delegate.contentLength();
        } catch (IOException e) {
            return -1;
        }
    }
 
    /**
     * 回调监听接口
     */
    public static interface Listener{
        /**
         * 暴露出上传进度
         * @param byteWritted  已经上传的字节大小
         * @param contentLength 文件的总字节大小
         */
        void onRequestProgress(long byteWritted, long contentLength);
    }
}
File file = new File(Environment.getExternalStorageDirectory(), "1.png");
if (!file.exists()){
    Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
}else{
    RequestBody requestBody2 = RequestBody.create(MediaType.parse("application/octet-stream"), file);
}
 
//使用我们自己封装的类
CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody2, new CountingRequestBody.Listener() {
    @Override
    public void onRequestProgress(long byteWritted, long contentLength) {
        //打印进度
        Log.d("pyh", "进度 :" + byteWritted + "/" + contentLength);
    }
});


目录
相关文章
|
JSON 数据格式 Docker
【Docker 基础教程】Centos7.5安装Docker并配置阿里云镜像
【Docker 基础教程】Centos7.5安装Docker并配置阿里云镜像
【Docker 基础教程】Centos7.5安装Docker并配置阿里云镜像
|
2月前
|
JavaScript 安全
URL编码/解码 在线工具分享
分享一款自研的URL编码/解码在线工具(Vue开发),支持encodeURI与encodeURIComponent两种模式。粘贴即转、一键复制,界面清爽无广告,附使用说明与编码对照表,轻松处理中文及特殊字符。
9383 2
|
1月前
|
大数据 数据库 数据库管理
EmEditor安装教程 Windows版:详细步骤+激活密钥输入+桌面快捷方式创建指南
EmEditor是功能强大的Windows文本编辑器,支持宏、Unicode及大数据/CSV处理,适用于网页设计、编程、出版、数据库与服务器管理等场景。本文详述其安装、激活(含终身密钥)及快捷方式创建方法。
|
2月前
|
存储 弹性计算 缓存
2026阿里云服务器最低价格:38元、99元、199元、898.20元四款云服务器区别与选购参考
阿里云在2026年活动中推出四款高性价比云服务器:轻量应用服务器(38元/年)、经济型e实例(99元/年)、通用算力型u1实例(199元/年)、通用算力型u2a实例(898.20元/年起)。这些服务器性能稳定,满足不同用户需求,如个人开发、中小网站、企业应用。轻量应用服务器适合入门级用户,经济型e实例适合个人开发者和小微企业,u1和u2a实例则分别适合追求稳定和更高性价比的企业用户。用户可根据需求和预算做出选择。
|
7月前
|
存储 机器学习/深度学习 数据采集
数据湖 vs 数据仓库:大厂为何总爱“湖仓并用”?
数据湖与数据仓库各有优劣,湖仓一体架构成为趋势。本文解析二者核心差异、适用场景及治理方案,助你选型落地。
数据湖 vs 数据仓库:大厂为何总爱“湖仓并用”?
|
Java 应用服务中间件 Spring
SpringBoot出现 java.lang.IllegalArgumentException: Request header is too large 解决方法
SpringBoot出现 java.lang.IllegalArgumentException: Request header is too large 解决方法
1112 0
|
安全 Java
在 Java 中使用实现 Runnable 接口的方式创建线程
【10月更文挑战第22天】通过以上内容的介绍,相信你已经对在 Java 中如何使用实现 Runnable 接口的方式创建线程有了更深入的了解。在实际应用中,需要根据具体的需求和场景,合理选择线程创建方式,并注意线程安全、同步、通信等相关问题,以确保程序的正确性和稳定性。
722 11
|
Docker 容器
docker设置国内镜像源
docker设置国内镜像源
46735 5
http代理ip按流量划算还是个数划算?
http代理ip按流量划算还是个数划算?
|
传感器 机器学习/深度学习 运维
预测性维护
预测性维护