博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
OkHttp3的简单使用(二)
阅读量:6651 次
发布时间:2019-06-25

本文共 6807 字,大约阅读时间需要 22 分钟。

OkHttp3的简单封装

public class OkHttpUtil {   public static final String TAG="OkHttpUtil";   private static OkHttpClient client;   private static OkHttpUtil httpUtil;   private OkHttpUtil(){      client=new OkHttpClient.Builder()            .connectTimeout(10, TimeUnit.SECONDS)            .readTimeout(10,TimeUnit.SECONDS)            .build();   }// 使用单例模式,保证只有一个OkHttpUtil和OkHttpClient 的实例。   public static OkHttpUtil getInstance(){      synchronized (OkHttpUtil.class){         if(httpUtil==null){            httpUtil= new OkHttpUtil();            return httpUtil;         }      }      return httpUtil;   }   /**    * get异步请求    * @param url    */   public static void getData(String url){      Request request=new Request.Builder().url(url)            .build();      client.newCall(request).enqueue(new Callback() {         @Override         public void onFailure(Call call, IOException e) {         }         @Override         public void onResponse(Call call, Response response) throws IOException {            //字符串类型            Log.i(TAG, "getData: " + response.body().string());            //字节数组类型            Log.i(TAG, "getData: " + response.body().bytes());            //字节流类型            Log.i(TAG, "getData: " + response.body().byteStream());            //字符流类型            Log.i(TAG, "getData: " + response.body().charStream());         }      });   }   /**    * 带有多个参数的get请求    * @param url    * @param map    */   public void getParams(String url,Map
map){ String url1=url; if(map!=null&&map.size()>0){ for(String key:map.keySet()){ url1+="&"+key+"="+map.get(key); } } getData(url1); } /** * 提交单个键值对 * @param url * @param key * @param value */ public void postKeyValuePaire(String url,String key,String value){ FormBody formBody=new FormBody.Builder() .add(key,value) .build(); Request request=new Request.Builder() .url(url) .post(formBody) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * 提交多个键值对 * * @param url 提交的路径 * @param map 用来放置键值对,map的key对应键,value对应值 */ public void postMap(String url,Map
map){ FormBody.Builder formBody=new FormBody.Builder(); if(map!=null){ for(String key:map.keySet()){ formBody.add(key,map.get(key)); } } Request request=new Request.Builder().url(url) .post(formBody.build()) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * post提交Json数据 * @param url * @param content */ public void postString(String url,String content){ MediaType mediaType=MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody=RequestBody.create(mediaType,content); Request request=new Request.Builder() .url(url) .post(requestBody) .build(); client.newCall(request) .enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * 上传单一文件 */ public void uploadFile(String url, File file, Callback callback){ MediaType type=MediaType.parse(getMediaType(file.getName()));//设置上传文件的类型 MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(type, file)); RequestBody requestBody = builder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); client.newCall(request).enqueue(callback); } /** * 上传多个文件 * @param url * @param files */ public void uploadFiles(String url,File[] files){ MultipartBody.Builder builder=new MultipartBody .Builder() .setType(MultipartBody.FORM); for(int i = 0; i
map){ MultipartBody.Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM); //添加文件 if(files!=null&&files.length>0){ for(int i=0;i
0){ for(String key:map.keySet()){ builder.addFormDataPart(key,map.get(key)); } } Request request=new Request.Builder().url(url) .post(builder.build()) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * 根据文件的名称判断文件的MediaType * @param fileName 文件名 * @return 文件的MediaType */ private String getMediaType(String fileName){ FileNameMap map= URLConnection.getFileNameMap(); String contentTypeFor=map.getContentTypeFor(fileName); if(contentTypeFor==null){ contentTypeFor="applicationn/octet-stream"; } return contentTypeFor; } /** * 设置请求头 * @param headersParams 请求头参数 * @return headers */ private Headers SetHeaders(Map
headersParams){ Headers headers=null; okhttp3.Headers.Builder headersbuilder=new okhttp3.Headers.Builder(); if(headersParams != null) { Iterator
iterator = headersParams.keySet().iterator(); String key = ""; while (iterator.hasNext()) { key = iterator.next().toString(); headersbuilder.add(key, headersParams.get(key)); Log.d("get http", "get_headers==="+key+"===="+headersParams.get(key)); } } headers=headersbuilder.build(); return headers; } /** * get方法连接拼加参数 * @param mapParams 参数 * @return 拼接后的url */ private String setUrlParams(Map
mapParams){ String strParams = ""; if(mapParams != null){ Iterator
iterator = mapParams.keySet().iterator(); String key = ""; while (iterator.hasNext()) { key = iterator.next().toString(); strParams += "&"+ key + "=" + mapParams.get(key); } } return strParams; }}

  

转载于:https://www.cnblogs.com/wangjiaghe/p/6931244.html

你可能感兴趣的文章
VS2012 调试Web项目 遭遇 HTTP 错误 500.23 - Internal Server Error
查看>>
tracker-store and tracker-miner-fs eating up my CPU on every startup
查看>>
Codeforces Round #248 (Div. 1) A. Ryouko's Memory Note 水题
查看>>
thinkphp使用自定义类方法
查看>>
[算法] 冒泡排序
查看>>
[LintCode] Two Sum 两数之和
查看>>
Linux高并发机制——epoll模型
查看>>
SQL注入与Java
查看>>
那些强悍的PHP一句话后门
查看>>
C# 文件下载 : WebClient
查看>>
vm装mac时,报VMware Workstation 不可恢复错误: (vcpu-0)
查看>>
JavaScript Ajax之美
查看>>
OpenGl从零开始之坐标变换
查看>>
oracle linux 启动
查看>>
C# 一个多层循环中,break一次能跳出几个循环?
查看>>
(转)systemctl 命令完全指南
查看>>
php : 基础(4)
查看>>
脚本大全
查看>>
PostgreSQL 允许远程访问设置方法
查看>>
eclipse中project->clean的作用是什么
查看>>