Day6 快速学习OkHttp3的九大用法

本文详细介绍了OkHttp3的九大用法,包括导入与基本配置、发送Get和Post请求、同步与异步操作、文件上传、Cookie管理、以及OkHttp的封装,适合Java和Android开发者学习。通过实例展示了如何进行网络请求、文件上传下载和图片展示,帮助开发者更好地掌握OkHttp3的使用技巧。
摘要由CSDN通过智能技术生成
效果图:

点此进入目录:[干货] 十天 教你从创意到上线APP

一、OkHttp3的基本用法

OkHttp3是Java和Android都能用,Android还有一个著名网络库叫Volley,那个只有Android能用。

导入OkHttp3

在gradle中添加依赖:

    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.squareup.okhttp3:okio-1.8.0.jar'

1、发送Get请求

String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
    .url(url)
    .build();
Call call = okHttpClient.newCall(request);
try {
    Response response = call.execute();
    System.out.println(response.body().string());
} catch (IOException e) {
    e.printStackTrace();
}

如果你需要在request的的header添加参数。例如Cookie,User-Agent什么的,这样:

Request request = new Request.Builder()
    .url(url)
    .header("键", "值")
    .header("键", "值")
    ...
    .build();

response的body有很多种输出方法,string()只是其中之一,注意是string()不是toString()。如果是下载文件就是response.body().bytes()。另外可以根据response.code()获取返回的状态码。

2、发送Post请求

String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();

RequestBody body = new FormBody.Builder()
    .add("键", "值")
    .add("键", "值")
    ...
    .build();

Request request = new Request.Builder()
    .url(url)
    .post(body)
    .build();

Call call = okHttpClient.newCall(request);
try {
    Response response = call.execute();
    System.out.println(response.body().string());
} catch (IOException e) {
    e.printStackTrace();
}

post请求创建request和get是一样的,只是post请求需要提交一个表单,就是RequestBody。表单的格式有好多种,普通的表单是:

RequestBody body = n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值