Android okhttp使用的方法
简介
OKHttp是一个十分常用的网络请求框架了,用于android中请求网络。
除了OKHttp,如今Android中主流的网络请求框架有:
- Android-Async-Http
- Volley
- OkHttp
- Retrofit
依赖库导入
在build.gradle 添加如下依赖
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
get请求
/** * 同步Get同求 * * @param url url * @return */ public String syncGet(String url) { String result = ""; //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(url) .get() .build(); final Call call = okHttpClient.newCall(request); //4.同步调用会阻塞主线程,这边在子线程进行 new Thread(new Runnable() { @Override public void run() { try { //同步调用,返回Response,会抛出IO异常 Response response = call.execute(); } catch (IOException e) { e.printStackTrace(); } } }).start(); return result; } /** * 异步Get同求 * * @param url url * @return */ public void nonSyncGet(String url, Callback responseCallback) { String result = null; //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); //2.创建Request对象 Request request = new Request.Builder() .url(url) .get() .build(); Call call =okHttpClient.newCall(request); call.enqueue(responseCallback); }
Post请求
在OkHttp中用Post方法把键值对数据传送到服务器,使用FormBody.Builder创建请求的参数键值,构建一个RequestBody对象,
- key-value:提交键值对
- String:字符串类型
- Form:表单数据
- Stream:流类型
- File:文件类型
/** * 同步Post同求 * * @param url url * @return */ public String syncPost(String url) { String result = null; //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); FormBody.Builder mBuild = new FormBody.Builder(); mBuild.add("name", "tony") .add("age", "21"); RequestBody requestBody= mBuild.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { result = response.body().string(); } else { throw new IOException("Unexpected code " + response); } } catch (IOException e) { e.printStackTrace(); } return result; } /** * 异步Post同求 * * @param url url * @return */ public void nonSyncPost(String url, Callback responseCallback) { //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); FormBody.Builder mBuild = new FormBody.Builder(); mBuild.add("name", "tony") .add("age", "21"); RequestBody requestBody= mBuild.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); try { okHttpClient.newCall(request).enqueue(responseCallback); } catch (Exception e) { e.printStackTrace(); } } /** * Post json * * @param url url * @return */ public String postJson(String url, Callback responseCallback) { String result = null; String jsonStr = "json"; //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create(mediaType, jsonStr); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { result = response.body().string(); } else { throw new IOException("Unexpected code " + response); } } catch (IOException e) { e.printStackTrace(); } return result; } /** * Post String * * @param url url * @return */ public String postString(String url, Callback responseCallback) { String result = null; //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:tony;password:123456}"); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { result = response.body().string(); } else { throw new IOException("Unexpected code " + response); } } catch (IOException e) { e.printStackTrace(); } return result; }
post表单请求
/** * Post 表单 * * @param url url * @return */ public String postForm(String url, Callback responseCallback) { String result = null; //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); MultipartBody.Builder mBuild = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("username", "tony") .addFormDataPart("password", "123456"); RequestBody requestBody= mBuild.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { result = response.body().string(); } else { throw new IOException("Unexpected code " + response); } } catch (IOException e) { e.printStackTrace(); } return result; }
post 上传文件
public void uploadFile(String url) { ArrayList<String> filelist = getFileList(); //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM); for (int i = 0; i < filelist.size(); i++) { String path = filelist.get(i); File file = new File(path); String fileMimeType = getMimeType(file); //这里获取文件类型,方法自己定义 MediaType mediaType = MediaType.parse(fileMimeType); RequestBody fileBody = RequestBody.create(mediaType, file); multipartBody.addFormDataPart("file" + i, file.getName(), fileBody); } RequestBody requestBody = multipartBody.build(); Request requestPostFile = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = null; try { response = okHttpClient.newCall(requestPostFile).execute(); if (response.isSuccessful()) { } else { throw new IOException("Unexpected code " + response); } } catch (IOException e) { e.printStackTrace(); } }
参考博文
https://www.jianshu.com/p/bb57bc65e4ce
https://www.jianshu.com/p/b1cf0b574e74
到此这篇关于Android okhttp使用的文章就介绍到这了,更多相关Android okhttp使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Android ViewModel与Lifecycles和LiveData组件用法详细讲解
JetPack是一个开发组件工具集,他的主要目的是帮助我们编写出更加简洁的代码,并简化我们的开发过程。JetPack中的组件有一个特点,它们大部分不依赖于任何Android系统版本,这意味者这些组件通常是定义在AndroidX库当中的,并且拥有非常好的向下兼容性2023-01-01详解Android TextView属性ellipsize多行失效的解决思路
这篇文章主要介绍了Android TextView属性ellipsize多行失效的解决思路,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-07-07
最新评论