Okhttp基础用法介绍

OKHttp是处理网络请求的开源框架,Andorid当前最火热的网络框架,Retrofit的底层也是OKHttp,用于替换HttpUrlConnectionApache HttpClient(API23 6.0已经移除)。

概况起来说OKHttp是一款优秀HTTP框架,它支持GET和POST请求,支持Http的文件上传和下载,支持加载图片,支持下载文件透明的GZIP压缩,支持响应缓存避免重复的网络请求,支持使用连接池来降低响应延迟的问题。

OKHttp的优点:

1.支持HTTP2/SPDY,这使得对同一个主机发出的所有请求都可以共享相同的套接字连接。

2.如果HTTP2/SPDY不可用OkHttp,会使用连接池来复用连接以提高效率。

3.提供了对 GZIP 的默认支持来降低传输内容的大小

4.提供了对 HTTP 响应的缓存机制,可以避免不必要的网络请求

5.当网络出现问题时,OkHttp会自动重试一个主机的多个 IP 地址

版本不同可能代码示例写法上存在一定的差异

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.11.0</version>
</dependency>
OkHttpClient默认的connectTimeout,readTimeout,writeTimeout都是10秒

post JSON格式请求

public void post() throws IOException {
    String jsonStr = "{\"test\":\"123456\"}";
    // 设置RequestBody MediaType
    RequestBody requestBody = RequestBody.create(jsonStr, MediaType.parse("application/json"));
    // 创建post请求
    Request request = new Request.Builder()
       .url("http://test")
       .post(requestBody)
       .build();
    OkHttpClient okHttpClient = new OkHttpClient()
       .newBuilder()
       .build();
    Response response = okHttpClient.newCall(request).execute();
    // 返回得body内容
    response.body().string();

}

post Form表单提交

public void postForm() throws IOException {
    // 构建form表单提交内容
    FormBody.Builder formBuild  = new FormBody.Builder();
    formBuild.add("userName","test");
    formBuild.add("password", "123456");

    // 创建post请求
    Request request = new Request.Builder()
       .url("http://test")
       .post(formBuild.build())
       .build();
    OkHttpClient okHttpClient = new OkHttpClient()
       .newBuilder()
       .build();
    Response response = okHttpClient.newCall(request).execute();
    // 返回得body内容
    response.body().string();
}

get请求

public void get()  throws IOException{
    OkHttpClient okHttpClient = new OkHttpClient()
       .newBuilder()
       .build();
    Request request = new Request.Builder()
       .get()
       .url("http://test?userName=zhangsan")
       .build();
    Response response = okHttpClient.newCall(request).execute();
    // 返回得body内容
    response.body().string(); 
}

请求头设置

public void setHeader()  throws IOException {
    OkHttpClient okHttpClient = new OkHttpClient()
       .newBuilder()
       .build();

    Request.Builder requestBuilder = new Request.Builder();
    // 设置请求头token
    requestBuilder.addHeader("token", "123456");
    Request request = requestBuilder
       .get()
       .url("http://test?userName=zhangsan")
       .build();
    Response response = okHttpClient.newCall(request).execute();
    // 返回得body内容
    response.body().string();
}

代理设置

public void setProxy()  throws IOException {
    // 构建代理对象
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
    OkHttpClient okHttpClient = new OkHttpClient()
       .newBuilder()
        // 设置代理对象
       .proxy(proxy)
       .build();

    Request request = new Request.Builder()
       .get()
       .url("http://test?userName=zhangsan")
       .build();
    Response response = okHttpClient.newCall(request).execute();
    // 返回得body内容
    response.body().string();
}

请求参数设置

    public void setConnectParam()  throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient()
               .newBuilder()
                // 设置连接超时参数
               .connectTimeout(1, TimeUnit.MINUTES)
                // 设置连接池
                //.connectionPool()
                // 设置拦截器
                // .addInterceptor()
                // 设置缓存
                // .cache()
                // 设置协议
                // .protocols()
                // 设置写入超时
               .writeTimeout(1, TimeUnit.MINUTES)
                // 设置读取超时
               .readTimeout(1, TimeUnit.MINUTES)
               .build();

        Request request = new Request.Builder()
               .get()
               .url("http://test?userName=zhangsan")
               .build();
        Response response = okHttpClient.newCall(request).execute();
        // 返回得body内容
        response.body().string();
   }

异步请求

public void async() throws Exception{
    OkHttpClient okHttpClient = new OkHttpClient()
       .newBuilder()
       .build();
    RequestBody requestBody = RequestBody.create("", MediaType.parse("application/json"));
    // 创建post请求
    Request request = new Request.Builder()
       .url("http://test")
       .post(requestBody)
       .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {

       }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            // 异步响应
            String responseStr = response.body().string();
       }
   });
}

上传文件

public void uploadFile() {
    // 创建对象
    OkHttpClient okHttpClient = new OkHttpClient();
    File file = new File("D:/test.txt");
    // 设置上传文件类型
    MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
    // 创建请求体
    RequestBody requestBody = RequestBody.create(file, mediaType);
    Request request = new Request.Builder().url("http://baidu.com")
        .post(requestBody)
        .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(@NotNull Call call, @NotNull IOException e) {
            // 请求失败
        }

        @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            // 请求成功
        }
    });
}

下载文件

public void downLoadFile() {
    // 创建对象
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url("xxx").build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(@NotNull Call call, @NotNull IOException e) {
            
        }

        @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            InputStream inputStream = response.body().byteStream();
            try (FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/1.pgg"))) {
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                }
            }
        }
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

游侠小马哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值