okhttp

一:OkHttpClient依赖

implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'

二:okhttp完成get请求

在这里插入图片描述

//网络请求json串下载
public void getjson(String url){

    /**
     * okHttpClient: build()出来,作用:关联Request请求,关联Call
     * Request: build()出来,设置请求方式,网址
     * Call:执行请求 方法:失败,成功response.body().string();
     */
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.readTimeout(5, TimeUnit.SECONDS);//读取超时
    builder.connectTimeout(5,TimeUnit.SECONDS);//连接超时

    OkHttpClient client = builder.build();//获得一个客户端对象
    Request request = new Request.Builder().get().url(url).build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            //失败;
            Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            //成功
            json = response.body().string();
            Log.i(TAG, "onResponse: 内容"+json);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "内容:"+json, Toast.LENGTH_SHORT).show();
                }
            });
        }
    });
}

三:okhttp完成post请求

在这里插入图片描述

//post上传
public void postjson(HashMap<String,String> body, String url){
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();
    FormBody.Builder formBody = new FormBody.Builder();
    for (String k:body.keySet()){
        formBody.add(k,body.get(k));
    }
    FormBody build = formBody.build();
    Request request = new Request.Builder().url(url).post(build).build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i(TAG, "onFailure: 上传失败");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String string = response.body().string();
            Log.i(TAG, "onResponse: 上传成功,结果:"+string);
        }
    });
}

四:okhttp完成上传文件

在这里插入图片描述

//post上传音乐
public void postMedia(String url){
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).connectTimeout(5, TimeUnit.SECONDS).build();
    MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "test.mp3", RequestBody.create(MediaType.parse("media.mp3"), new File("/mnt/sdcard/2.jpg"))).build();
    Request request = new Request.Builder().url(url).post(body).build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i(TAG, "onFailure: 上传失败");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String string = response.body().string();
            Log.i(TAG, "onResponse: 成功:"+string);
        }
    });

五:拦截器

1.什么是拦截器

拦截网络操作

2.拦截器种类

桥、连接、日志、服务、缓存等

3.拦截器实际应用

HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    @Override
    public void log(String message) {
        Log.i(TAG, "log: "+message);
    }
});
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(5, TimeUnit.SECONDS);//读取超时
builder.connectTimeout(5,TimeUnit.SECONDS);//连接超时

builder.addInterceptor(interceptor);

消息头

//添加消息头
public void addHeader(){
    //拦截器
    interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder().addHeader("token","1").build();
            return chain.proceed(request);//开始拦截
        }
    };
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值