当前位置:   article > 正文

OkHttp3 使用简介_okhhtp3 用法

okhhtp3 用法

注意:在配置完以下依赖,请求时失败请配置标红代码

 android:usesCleartextTraffic="true"

配置:

  1. <application
  2. android:allowBackup="true"
  3. android:icon="@mipmap/ic_launcher"
  4. android:label="@string/app_name"
  5. android:roundIcon="@mipmap/ic_launcher_round"
  6. android:supportsRtl="true"
  7. android:usesCleartextTraffic="true"
  8. android:theme="@style/AppTheme">
  9. ***
  10. </application>

参考:Android高版本联网失败报错:Cleartext HTTP traffic to xxx not permitted解决方法_android studio xml can't determine type for tag_柚子君.的博客-CSDN博客

一,简介

OkHttp 是一个高效的 HTTP 客户端,具有非常多的优势:

  1. 能够高效的执行 http,数据加载速度更快,更省流量
  2. 支持 GZIP 压缩,提升速度,节省流量
  3. 缓存响应数据,避免了重复的网络请求
  4. 使用简单,支持同步阻塞调用和带回调的异步调用

OkHttp 支持 Android2.3 以上,JDK1.7 以上。

官网地址:Overview - OkHttp
github地址:GitHub - square/okhttp: Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

二,基本用法

添加 OkHttp3 依赖:

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

添加json字符串转换成实体类依赖:

implementation 'com.google.code.gson:gson:2.8.5'
最新的版本号可以在官网和github上找到

创建OkHttpClient实例

  1. //方式一:创建OkHttpClient实例,使用默认构造函数,创建默认配置OkHttpClient(官方建议全局只有一个实例)
  2. OkHttpClient okHttpClient = new OkHttpClient();
  3. //方式二:通过new OkHttpClient.Builder() 一步步配置一个OkHttpClient实例
  4. OkHttpClient httpClient = new OkHttpClient.Builder().connectTimeout(13, TimeUnit.SECONDS).build();
  5. //方式三:如果要求使用现有的实例,可以通过newBuilder().build()方法进行构造
  6. OkHttpClient client = okHttpClient.newBuilder().build();

1. get 请求

使用 OkHttp 进行 get 请求只需要四个步骤

  1. 新建 OkHttpClient对象
  2. 构造 Request 对象
  3. 将 Request 对象封装为 Call
  4. 通过 Call 来执行同步或异步请求
  1. OkHttpClient client = new OkHttpClient();
  2. Request request = new Request.Builder()
  3. .url(HttpTools.getAllUserUrl)
  4. .get() //默认为GET请求,可以不写
  5. .build();
  6. Call call = client.newCall(request);
  7. call.enqueue(new Callback() {
  8. @Override
  9. public void onFailure(Call call,IOException e) {
  10. runOnUiThread(new Runnable() {
  11. @Override
  12. public void run() {
  13. Toast.makeText(getApplicationContext(), "请求失败!", Toast.LENGTH_SHORT).show();
  14. }
  15. });
  16. }
  17. @Override
  18. public void onResponse(Call call,Response response) throws IOException {
  19. final String str = response.body().string();
  20. runOnUiThread(new Runnable() {
  21. @Override
  22. public void run() {
  23. Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
  24. }
  25. });
  26. }
  27. });

后台代码:

  1. // 查询用户全部数据
  2. @RequestMapping("/showInfo")
  3. @ResponseBody
  4. public String getUsers(ModelMap map){
  5. map.addAttribute("users",serviceImpl.queryAll());
  6. System.out.println(map.get("users"));
  7. return "userInfo";
  8. }

1.1 get 同步请求

通过 call.excute() 方法来提交同步请求,这种方式会阻塞线程,而为了避免 ANR 异常,Android3.0 之后已经不允许在主线程中访问网络了
所以 OkHttp 的同步 get 请求需要开启一个子线程:

  1. new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. try {
  5. // 同步请求
  6. Response response = call.execute();
  7. Log.d(TAG, response.body().toString());
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }).start();

1.2 get 异步请求

通过 call.enqueue(Callback)方法来提交异步请求

  1. // 异步请求
  2. call.enqueue(new Callback() {
  3. @Override
  4. public void onFailure(Call call, IOException e) {
  5. Log.d(TAG, "onFailure: " + e);
  6. }
  7. @Override
  8. public void onResponse(Call call, Response response) throws IOException {
  9. Log.d(TAG, "OnResponse: " + response.body().toString());
  10. }
  11. });

2. post 请求

post同步、异步请求和get的同步异步请求方式一样(execute(同步) enqueue(异步)

2.1 FormBody表单形式请求

方式一:

  1. OkHttpClient client = new OkHttpClient();
  2. //创建表单请求参数
  3. FormBody.Builder builder = new FormBody.Builder();
  4. builder.add("username", userNameET.getText().toString());
  5. builder.add("password", passwordET.getText().toString());
  6. FormBody formBody = builder.build();
  7. Request request = new Request.Builder()
  8. .url(HttpTools.loginUrl)
  9. .post(formBody)
  10. .build();
  11. Call call = client.newCall(request);
  12. call.enqueue(new Callback() {
  13. @Override
  14. public void onFailure(Call call,IOException e) {
  15. runOnUiThread(new Runnable() {
  16. @Override
  17. public void run() {
  18. Toast.makeText(getApplicationContext(), "登录失败!", Toast.LENGTH_SHORT).show();
  19. }
  20. });
  21. }
  22. @Override
  23. public void onResponse(Call call, Response response) throws IOException {
  24. final String str = response.body().string();
  25. runOnUiThread(new Runnable() {
  26. @Override
  27. public void run() {
  28. Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
  29. }
  30. });
  31. }
  32. });

后台代码:

  1. /**
  2. * 用户登录 --- 传递参数
  3. * */
  4. @RequestMapping(value="/login", method=RequestMethod.POST)
  5. @ResponseBody// 将java对象转为json格式的数据。
  6. public String loginUser(@RequestParam("username")String username,
  7. @RequestParam("password")String password) {
  8. // 设置值
  9. User user = new User();
  10. user.setUsername(username);
  11. user.setPassword(password);
  12. int flag = serviceImpl.loginVerification(user);
  13. if (flag <= 0) {
  14. System.out.println("失败");
  15. return "error";
  16. }
  17. System.out.println("成功!");
  18. return "success";
  19. }

方式二 :

  1. OkHttpClient client = new OkHttpClient();
  2. //创建表单请求参数
  3. FormBody.Builder builder = new FormBody.Builder();
  4. builder.add("name", regName.getText().toString());
  5. builder.add("sex",regSex.getText().toString());
  6. builder.add("address", regAddress.getText().toString());
  7. builder.add("username", userName.getText().toString());
  8. builder.add("password", password.getText().toString());
  9. FormBody formBody = builder.build();
  10. Request request = new Request.Builder()
  11. .url(HttpTools.registerUrl)
  12. .post(formBody)
  13. .build();
  14. Call call = client.newCall(request);
  15. call.enqueue(new Callback() {
  16. @Override
  17. public void onFailure(Call call,IOException e) {
  18. runOnUiThread(new Runnable() {
  19. @Override
  20. public void run() {
  21. Toast.makeText(getApplicationContext(), "注册失败!", Toast.LENGTH_SHORT).show();
  22. }
  23. });
  24. }
  25. @Override
  26. public void onResponse(Call call, Response response) throws IOException {
  27. final String str = response.body().string();
  28. runOnUiThread(new Runnable() {
  29. @Override
  30. public void run() {
  31. Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
  32. finish();
  33. }
  34. });
  35. }
  36. });

后台代码:
 

  1. /**
  2. * 用户注册 --- 传递对象
  3. * */
  4. @RequestMapping(value="/register", method=RequestMethod.POST)
  5. @ResponseBody
  6. public String registerUser(User user) {
  7. serviceImpl.registerUser(user);
  8. return "success";
  9. }

方式三:

  1. String webUrl = "http://47.112.180.188:8080/renren-fast/app/login";
  2. // 创建OKHttpClient
  3. OkHttpClient client = new OkHttpClient.Builder().build();
  4. // 创建参数
  5. Map m = new HashMap();
  6. m.put("mobile",account);
  7. m.put("password",pwd);
  8. // 参数转换成json字符串
  9. JSONObject jsonObject = new JSONObject(m);
  10. String jsonStr = jsonObject.toString();
  11. RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),
  12. jsonStr);
  13. // 创建Request
  14. Request request = new Request.Builder()
  15. .url(webUrl)
  16. .addHeader("contentType","application/json;charset=utf-8")
  17. .post(requestBodyJson)
  18. .build();
  19. // 创建Call
  20. Call call = client.newCall(request);
  21. call.enqueue(new Callback() {
  22. @Override
  23. public void onFailure(Call call,IOException e) {
  24. Log.e("onFailure",e.getMessage());
  25. }
  26. @Override
  27. public void onResponse(Call call,Response response) throws IOException {
  28. String result = response.body().string();
  29. System.out.println(result);
  30. }
  31. });

2.2 解释一下 


Content-Type(MediaType),即是Internet Media Type,互联网媒体类型;也叫做MIME类型,在Http协议消息头中,使用Content-Type来表示具体请求中的媒体类型信息。用于定义网络文件的类型和网页的编码,决定文件接收方将以什么形式、什么编码读取这个文件。常见的媒体格式类型有:

  • text/html:HTML格式
  • text/pain:纯文本格式
  • image/jpeg:jpg图片格式
  • application/json:JSON数据格式
  • application/octet-stream:二进制流数据(如常见的文件下载)
  • application/x-www-form-urlencoded:form表单encType属性的默认格式,表单数据将以key/value的形式发送到服务端
  • multipart/form-data:表单上传文件的格式

使用 create 方法可以用来用于上传 String 和 File 对象,具体实现如下:
上传JSON字符串:

  1. OkHttpClient client = new OkHttpClient();
  2. //指定当前请求的 contentType 为 json 数据
  3. MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  4. String jsonStr = "{\"name\":\"zhangsan\",\"age\":\"20\"}";
  5. Request request = new Request.Builder()
  6. .url(url)
  7. .post(RequestBody.create(JSON, jsonStr))
  8. .build();
  9. client.newCall(request).enqueue(new Callback() {
  10. @Override
  11. public void onFailure(Call call, IOException e) {
  12. }
  13. @Override
  14. public void onResponse(Call call, Response response) throws IOException {
  15. }
  16. });

上传文件:

  1. OkHttpClient client = new OkHttpClient();
  2. File file = new File(filePath);
  3. Request request = new Request.Builder()
  4. .url(url)
  5. .post(RequestBody.create(MediaType.parse("application/octet-stream"), file))
  6. .build();
  7. client.newCall(request).enqueue(new Callback() {
  8. @Override
  9. public void onFailure(Call call, IOException e) {
  10. }
  11. @Override
  12. public void onResponse(Call call, Response response) throws IOException {
  13. }
  14. });

2.3 使用MultipartBody同时上传多种类型数据

多文件和键值对同时上传

  1. File file = new File(filePath);
  2. MediaType mediaType = MediaType.parse("application/octet-stream;charset=utf-8");
  3. MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
  4. multipartBodyBuilder.setType(MultipartBody.FORM);
  5. // 传递参数
  6. multipartBodyBuilder.addFormDataPart("file",file.getName(),RequestBody.create(mediaType,file));
  7. multipartBodyBuilder.addFormDataPart("name","张三");
  8. multipartBodyBuilder.addFormDataPart("age","23");
  9. //构建请求体
  10. RequestBody requestBody = multipartBodyBuilder.build();
  11. OkHttpClient client = new OkHttpClient();
  12. Request request = new Request.Builder()
  13. .url(HttpTools.upLoadFile)
  14. .post(requestBody)
  15. .build();
  16. client.newCall(request).enqueue(new Callback() {
  17. @Override
  18. public void onFailure(Call call, IOException e) {
  19. runOnUiThread(new Runnable() {
  20. @Override
  21. public void run() {
  22. Toast.makeText(getApplicationContext(), "上传失败!", Toast.LENGTH_SHORT).show();
  23. }
  24. });
  25. }
  26. @Override
  27. public void onResponse(Call call, Response response) throws IOException {
  28. final String str = response.body().string();
  29. runOnUiThread(new Runnable() {
  30. @Override
  31. public void run() {
  32. Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
  33. }
  34. });
  35. }
  36. });

后台代码

  1. @RequestMapping(value="/upload",method=RequestMethod.POST)
  2. @ResponseBody
  3. public String upLoadFile(@RequestParam("file") MultipartFile upFile,
  4. @RequestParam("name") String name,
  5. @RequestParam("age") String age,
  6. HttpServletRequest request,
  7. HttpServletResponse response) {
  8. System.out.println(upFile.getName());
  9. System.out.println(name);
  10. System.out.println(age);
  11. // 判断文件手否有内容
  12. if (!upFile.isEmpty()) {
  13. // 先设定一个放置上传文件的文件夹(该文件夹可以不存在,下面会判断创建)
  14. String deposeFilesDir = "C:\\Users\\admin\\Desktop\\file\\";
  15. // 获取附件原名(有的浏览器如chrome获取到的是最基本的含 后缀的文件名,如myImage.png)
  16. // 获取附件原名(有的浏览器如ie获取到的是含整个路径的含后缀的文件名,如C:\\Users\\images\\myImage.png)
  17. String fileName = upFile.getOriginalFilename();
  18. // 如果是获取的含有路径的文件名,那么截取掉多余的,只剩下文件名和后缀名
  19. int index = fileName.lastIndexOf("\\");
  20. if (index > 0) {
  21. fileName = fileName.substring(index + 1);
  22. }
  23. // 判断单个文件大于1M
  24. long fileSize = upFile.getSize();
  25. if (fileSize > 1024 * 1024) {
  26. System.out.println("文件大小为(单位字节):" + fileSize);
  27. System.out.println("该文件大于1M");
  28. }
  29. // 当文件有后缀名时
  30. if (fileName.indexOf(".") >= 0) {
  31. // split()中放正则表达式; 转义字符"\\."代表 "."
  32. String[] fileNameSplitArray = fileName.split("\\.");
  33. // 加上random戳,防止附件重名覆盖原文件
  34. fileName = fileNameSplitArray[0] + (int) (Math.random() * 100000) + "." + fileNameSplitArray[1];
  35. }
  36. // 当文件无后缀名时(如C盘下的hosts文件就没有后缀名)
  37. if (fileName.indexOf(".") < 0) {
  38. // 加上random戳,防止附件重名覆盖原文件
  39. fileName = fileName + (int) (Math.random() * 100000);
  40. }
  41. System.out.println("fileName:" + fileName);
  42. // 根据文件的全路径名字(含路径、后缀),new一个File对象dest
  43. File dest = new File(deposeFilesDir + fileName);
  44. // 如果该文件的上级文件夹不存在,则创建该文件的上级文件夹及其祖辈级文件夹;
  45. if (!dest.getParentFile().exists()) {
  46. dest.getParentFile().mkdirs();
  47. }
  48. try {
  49. // 将获取到的附件file,transferTo写入到指定的位置(即:创建dest时,指定的路径)
  50. upFile.transferTo(dest);
  51. } catch (IllegalStateException e) {
  52. // TODO Auto-generated catch block
  53. e.printStackTrace();
  54. } catch (IOException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. }
  58. System.out.println("文件的全路径名字(含路径、后缀)>>>>>>>" + deposeFilesDir + fileName);
  59. return "success";
  60. }
  61. return "error";
  62. }

下载文件

  1. OkHttpClient client = new OkHttpClient();
  2. Request request = new Request.Builder()
  3. .url(HttpTools.downloadFile+"?fileName=test.jpg")
  4. .get()
  5. .build();
  6. Call call = client.newCall(request);
  7. call.enqueue(new Callback() {
  8. @Override
  9. public void onFailure(Call call,IOException e) {
  10. runOnUiThread(new Runnable() {
  11. @Override
  12. public void run() {
  13. Toast.makeText(getApplicationContext(), "下载失败!", Toast.LENGTH_SHORT).show();
  14. }
  15. });
  16. }
  17. @Override
  18. public void onResponse(Call call, Response response) throws IOException {
  19. InputStream ins = response.body().byteStream();
  20. Bitmap bitmap = BitmapFactory.decodeStream(ins);
  21. File galleyFile = new File(getExternalFilesDir("图片下载").getPath());
  22. File temp = new File(galleyFile.getPath());//要保存文件先创建文件夹
  23. if (!temp.exists()) {
  24. temp.mkdir();
  25. }
  26. // 图片名称
  27. String imgName = new Date().getTime() + ".jpg";
  28. //将要保存图片的路径和图片名称
  29. File file=new File(galleyFile.getPath()+File.separator+imgName);
  30. try {
  31. BufferedOutputStream bos= new BufferedOutputStream(new FileOutputStream(file));
  32. // 压缩图片
  33. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
  34. int len = 0;
  35. byte[] buffer = new byte[1024];
  36. while ((len = ins.read(buffer,0,buffer.length))!=-1){
  37. bos.write(buffer,0,buffer.length);
  38. bos.flush();
  39. }
  40. bos.close();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. });

后台代码

  1. /**
  2. * 下载文件(下载到客户端)
  3. */
  4. @RequestMapping(value = "/download",method = RequestMethod.GET)
  5. @ResponseBody
  6. public void getFile(@RequestParam("fileName") String fileName,
  7. HttpServletRequest request,
  8. HttpServletResponse response) {
  9. //String fileName = "test.jpg";
  10. // 文件名转码,避免中文乱码
  11. String codeFileName = null;
  12. try {
  13. codeFileName = URLEncoder.encode(fileName,"UTF-8");
  14. }
  15. catch (UnsupportedEncodingException e1) {
  16. // TODO Auto-generated catch block e1.printStackTrace(); }
  17. }
  18. /*
  19. *
  20. * tomcat_path -- E:/apache-tomcat-8/webapps/SSM/file
  21. *
  22. *String tomcat_path = request.getSession().getServletContext().getRealPath("file");
  23. *
  24. */
  25. // 文件路径(fileName 传递过来的文件名)
  26. String downloadFilePath = "C:\\Users\\admin\\Desktop\\file\\"+codeFileName;
  27. File imageFile = new File(downloadFilePath);
  28. if (imageFile.exists()) {
  29. FileInputStream fis = null;
  30. OutputStream os = null;
  31. try {
  32. fis = new FileInputStream(imageFile);
  33. os = response.getOutputStream();
  34. int count = 0;
  35. byte[] buffer = new byte[1024 * 8];
  36. while ((count = fis.read(buffer,0,buffer.length)) != -1) {
  37. os.write(buffer, 0, count);
  38. os.flush();
  39. }
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. } finally {
  43. try {
  44. fis.close();
  45. os.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. }

2.4 使用post请求上传json类型数据

在工程中导入:

dependencies { 

  1. // 阿里巴巴fastJson
  2. //implementation 'com.alibaba:fastjson:1.2.49'

  implementation ‘com.alibaba:fastjson:1.1.54.android’ 
}

  1. try {
  2. // 创建json对象
  3. JSONObject jsonObject = new JSONObject();
  4. // 创建数组
  5. ArrayList<String> arrayList = new ArrayList();
  6. HashMap<String,String> map = new HashMap<>();
  7. for (int i=0; i < 5; i++ ){
  8. map.put(String.valueOf(i), "数据"+i);
  9. }
  10. arrayList.add(com.alibaba.fastjson.JSONObject.toJSONString(map));
  11. // 数组参数
  12. jsonObject.put("arrList",arrayList);
  13. // 字符串参数
  14. jsonObject.put("appId", "appId");
  15. jsonObject.put("token", "token");
  16. jsonObject.put("clientId", "clientId");
  17. String data = jsonObject.toString();
  18. // 构造请求体
  19. RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), data);
  20. Request request = new Request.Builder()
  21. .url(url)
  22. .post(body)
  23. .build();
  24. // 向服务器异步请求数据
  25. OkHttpClient okHttpClient = new OkHttpClient();
  26. okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
  27. @Override
  28. public void onFailure(okhttp3.Call call, IOException e) {
  29. Toast.makeText(getApplicationContext(),"失败", Toast.LENGTH_SHORT).show();
  30. //LogUtils.i(TAG, "失败");
  31. }
  32. @Override
  33. public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
  34. ResponseBody body = response.body();
  35. Toast.makeText(getApplicationContext(),body.toString(), Toast.LENGTH_SHORT).show();
  36. //LogUtils.i(TAG, "返回数据:" + body.string());
  37. }
  38. });
  39. } catch (JSONException e) {
  40. e.printStackTrace();
  41. }

后台代码:

  1. // 参数为json,参数前用注解@RequestBody,返回值为json,在方法上用注解@RequestBody
  2. @RequestMapping(value="/json_method", method=RequestMethod.POST)
  3. public String jsonMethod(@RequestBody String jsonStr){
  4. System.out.println("jsonStr:"+jsonStr);
  5. return "success"// 跳转的页面名称
  6. }

3. Call 请求器

OkHttp 客户端负责接收应用程序发出的请求,并且从服务器获取响应返回给应用程序。理论听起来十分简单,但是在实践中往往会出现很多意想不到的问题。
通过配置 OkHttpClient,可以配置重写请求、重写响应、跟踪请求、重试请求等多种操作,这样一来你发送的一个简单请求可能就会变成需要发送多个请求以及接收多个响应后才能获得想要的响应。OkHttp 将这些多次的中间请求和响应任务建模成了一个 Call 对象,但是通常情况下中间请求及响应工作不会很多,令人欣慰的是,无论发生URL重定向还是因为服务器出现问题而向一个备用IP地址再次发送请求的情况,你的代码都将正常运行。
执行Call有两种方式:

  • 同步:请求和处理响应发生在同一线程。并且此线程会在响应返回之前会一直被堵塞。
  • 异步:请求和处理响应发生在不同线程。将发送请求操作发生在一个线程,并且通过回调的方式在其他线程进行处理响应。(一般在子线程发送请求,主线程处理响应)。

Calls可以在任何线程被取消。当这个Call尚未执行结束时,执行取消操作将会直接导致此Call失败!当一个Call被取消时,无论是写入请求主体或者读取响应主体的代码操作,都会抛出一个IOException异常。

4.Cookie存储/获取以及使用

cookie存/取工具类:

  1. package com.chy.https;
  2. import android.content.Context;
  3. import android.content.SharedPreferences;
  4. import java.util.List;
  5. import okhttp3.Cookie;
  6. /**
  7. * OKHttp3 cookies存/取类
  8. * */
  9. public class OkHttp3Cookie {
  10. private static final String COOKIE_FLAG = "COOKIE_FLAG";
  11. private static final String COOKIE_VAL = "COOKIE_VAL";
  12. /**
  13. * 存储cookie
  14. * */
  15. public static void saveCookies(Context context,List<Cookie> cookies){
  16. if (cookies.isEmpty())
  17. return;
  18. Cookie cookie = cookies.get(0);
  19. String name = cookie.name();
  20. String value = cookie.value();
  21. SharedPreferences cookie_sp = context.getSharedPreferences(COOKIE_FLAG,Context.MODE_PRIVATE);
  22. SharedPreferences.Editor edit = cookie_sp.edit();
  23. edit.putString(COOKIE_VAL,name+"="+value);
  24. edit.apply();
  25. }
  26. /**
  27. * 获取cookie
  28. * */
  29. public static String getCookies(Context context){
  30. SharedPreferences cookie_sp = context.getSharedPreferences(COOKIE_FLAG,Context.MODE_PRIVATE);
  31. String cookieVal = cookie_sp.getString(COOKIE_VAL, null);
  32. return cookieVal;
  33. }
  34. }

使用示例:

存储

  1. // 获取cookies
  2. Headers headers = response.headers();
  3. List<Cookie> cookies = Cookie.parseAll(request.url(), headers);
  4. // 存储cookies
  5. OkHttp3Cookie.saveCookies(context,cookies);

使用

  1. // 获取cookie
  2. String cookieVal = OkHttp3Cookie.getCookies(context);
  3. // 创建Request
  4. Request request = new Request.Builder()
  5. .url(dataUrl)
  6. .addHeader("Cookie",cookieVal)
  7. .get()
  8. .build();

 

最后附赠安卓开发常用的几个第三方依赖网址

https://blog.csdn.net/qq_43143981/article/details/83718777

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/771737
推荐阅读
相关标签
  

闽ICP备14008679号