OkHttp简单使用
【摘要】
公众号:知识浅谈
0、okhttp简介
OkHttp是一个优秀的网络请求框架,目前主流已经替换httpclient, HttpURLConnection 使用方式;
OkHttp支持连接同...
公众号:知识浅谈
0、okhttp简介
OkHttp是一个优秀的网络请求框架,目前主流已经替换httpclient, HttpURLConnection 使用方式;
OkHttp支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,自带GZIP压缩,请求缓存等优势;
OkHttp 成为 Android 最常见的网络请求库, 但并不妨碍java后端学习他,所以这边知识追寻者 做了常用总结。
一、环境引入
maven项目
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
gradle
compile 'com.squareup.okhttp3:okhttp:3.6.0'
- 1
二、操作食用
GET的使用(包含同步和异步)
请求步骤
- 获取OkHttpClient对象
- 设置请求request
- 封装call
- 异步调用,并设置回调函数
public void get(String url){ // 1 获取OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // 2设置请求 Request request = new Request.Builder() .get() .url(url) .build(); // 3封装call Call call = client.newCall(request); // 4异步调用,并设置回调函数 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // ... } @Override public void onResponse(Call call, final Response response) throws IOException { if (response!=null && response.isSuccessful()){ // ... // response.body().string(); } } }); //同步调用,返回Response,会抛出IO异常 //Response response = call.execute(); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
POST的使用
form 表单形式
- 获取OkHttpClient对象
- 构建参数body
- 构建 request
- 将Request封装为Call
- 异步调用
public void postFormData(String url){ // 1 获取OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // 2 构建参数 FormBody formBody = new FormBody.Builder() .add("username", "admin") .add("password", "admin") .build(); // 3 构建 request Request request = new Request.Builder() .url(url) .post(formBody) .addHeader("添加","你的请求头的内容") .build(); // 4 将Request封装为Call Call call = client.newCall(request); // 同步调用 Response response = call.execute(); // 5 异步调用 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // ... } @Override public void onResponse(Call call, final Response response) throws IOException { if (response!=null && response.isSuccessful()){ // ... } } }); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
json参数形式
-
获取OkHttpClient对象
-
构建参数
-
构建 request
-
将Request封装为Call
-
异步调用
public void postForJson(String url, String json){ // 1 获取OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // 2 构建参数 RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); // 3 构建 request Request request = new Request.Builder() .url(url) .post(requestBody) .build(); // 4 将Request封装为Call Call call = client.newCall(request); //同步调用 Response response = call.execute(); // 5 异步调用 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // ... } @Override public void onResponse(Call call, final Response response) throws IOException { if (response!=null && response.isSuccessful()){ // ... } } }); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
如果是json字符串,替换请求媒体类型即可
// 2 构建参数 RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}"); // 3 构建 request Request request = new Request.Builder() .url(url) .post(requestBody) .build();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
文件下载
-
获取OkHttpClient对象
-
构建 request
-
异步调用
-
文件下载
/** * <p> 文件下载 </p> * @Param url 下载地址url * @Param target 下载目录 * @Param target 文件名 * @Return */ private void download(String url, String target, String fileName){ // 1 获取OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // 2构建 request Request request = new Request.Builder() .url(url) .build(); // 3 异步调用 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ // 4 文件下载 downlodefile(response, target,fileName); } } }); } private void downlodefile(Response response, String url, String fileName) { InputStream inputStream = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream outputStream = null; try { inputStream = response.body().byteStream(); //文件大小 long total = response.body().contentLength(); File file = new File(url, fileName); outputStream = new FileOutputStream(file); long sum = 0; while ((len = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, len); } outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
文件上传
-
获取OkHttpClient对象
-
封装参数以 form形式, 媒体格式为二进制流
-
封装 request
-
异步回调
/** * <p> 文件上传 </p> * @Param [url] * @Return */ public void upload(String url){ File file = new File("C:/mydata/generator/test.txt"); if (!file.exists()){ System.out.println("文件不存在"); }else{ // 获取OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // 2封装参数以 form形式 RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("username", "admin") .addFormDataPart("password", "admin") .addFormDataPart("file", "555.txt", RequestBody.create(MediaType.parse("application/octet-stream"), file)) .build(); // 3 封装 request Request request = new Request.Builder() .url(url) .post(requestBody) .build(); // 4 异步回调 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { } }); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
文章来源: englishcode.blog.csdn.net,作者:知识浅谈,版权归原作者所有,如需转载,请联系作者。
原文链接:englishcode.blog.csdn.net/article/details/120803291
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)