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);
    }
});


目录
相关文章
|
3天前
|
缓存
okhttp Interceptor
okhttp Interceptor
9 1
|
JSON Java Maven
自从用了 OkHttp,别的都完全不想用了!
自从用了 OkHttp,别的都完全不想用了!
163 0
|
设计模式 缓存 监控
OKHttp3 从使用到原理分析
Okhttp3 是我们经常使用的一个网络框架,可扩展性强,支持 get 缓存, spdy、http2.0,gzip 压缩减少数据流量,同步和异步请求,连接池复用机制等特性让广大 android 开发者深爱不已,今天我就带大家从 Okhttp 简单使用,到各种好用拦截器原理了解 Okhttp3
1184 0
OKHttp3 从使用到原理分析
|
编解码 安全 Java
我终于决定要放弃 okhttp、httpClient
在SpringBoot项目直接使用okhttp、httpClient或者RestTemplate发起HTTP请求,既繁琐又不方便统一管理。
|
存储 缓存 网络协议
源码阅读 | Okhttp
源码阅读 | Okhttp
|
设计模式 API
定制Retrofit
定制Retrofit
94 0
定制Retrofit
|
设计模式 Java API
【OkHttp】OkHttp 源码分析 ( 网络框架封装 | OkHttp 4 迁移 | OkHttp 建造者模式 )
【OkHttp】OkHttp 源码分析 ( 网络框架封装 | OkHttp 4 迁移 | OkHttp 建造者模式 )
308 0
【OkHttp】OkHttp 源码分析 ( 网络框架封装 | OkHttp 4 迁移 | OkHttp 建造者模式 )
|
XML JSON Java
再见,HttpClient!再见,Okhttp!
因为业务关系,要和许多不同第三方公司进行对接。这些服务商都提供基于http的api。但是每家公司提供api具体细节差别很大。有的基于RESTFUL规范,有的基于传统的http规范;有的需要在header里放置签名,有的需要SSL的双向认证,有的只需要SSL的单向认证;有的以JSON 方式进行序列化,有的以XML方式进行序列化。类似于这样细节的差别太多了。
411 0
再见,HttpClient!再见,Okhttp!
|
存储 Android开发 网络协议
浅谈OkHttp
本来想看看源码提高下自己的水平,以前也有看过某些框架的源码,但是基本都是只看某段,这次打算好好的研究一遍。本来是想拿RecyclerView的源码来开刀的,但是好像RecyclerView的代码没那么容易看懂,而且变量还贼多,还大量用了设计模式,讲真,看起来还真觉得挺费劲的。
1175 0
|
缓存 API Android开发
浅谈OkHttp以及Retrofit+RxJava的封装使用
1.为什么我们要使用OkHttp?OkHttp有什么优点?  说OkHttp之前我们先说另外两个网络请求库——HttpUrlConnection和HttpClient。
2162 0