okHttp封装使用
package com.zhy.utils.http.okhttp; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView; import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set; /**
* Created by zhy on 15/8/17.
*/
public class OkHttpClientManager
{
private static OkHttpClientManager mInstance;
private OkHttpClient mOkHttpClient;
private Handler mDelivery; private static final String TAG = "OkHttpClientManager"; private OkHttpClientManager()
{
mOkHttpClient = new OkHttpClient();
mDelivery = new Handler(Looper.getMainLooper());
} public static OkHttpClientManager getInstance()
{
if (mInstance == null)
{
synchronized (OkHttpClientManager.class)
{
if (mInstance == null)
{
mInstance = new OkHttpClientManager();
}
}
}
return mInstance;
} /**
* 同步的Get请求
*
* @param url
* @return Response
*/
private Response _getAsyn(String url) throws IOException
{
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response execute = call.execute();
return execute;
} /**
* 同步的Get请求
*
* @param url
* @return 字符串
*/
private String _getAsString(String url) throws IOException
{
Response execute = _getAsyn(url);
return execute.body().string();
} /**
* 异步的get请求
*
* @param url
* @param callback
*/
private void _getAsyn(String url, final StringCallback callback)
{
final Request request = new Request.Builder()
.url(url)
.build();
deliveryResult(callback, request);
} /**
* 同步的Post请求
*
* @param url
* @param params post的参数
* @return
*/
private Response _post(String url, Param... params) throws IOException
{
Request request = buildPostRequest(url, params);
Response response = mOkHttpClient.newCall(request).execute();
return response;
} /**
* 同步的Post请求
*
* @param url
* @param params post的参数
* @return 字符串
*/
private String _postAsString(String url, Param... params) throws IOException
{
Response response = _post(url, params);
return response.body().string();
} /**
* 异步的post请求
*
* @param url
* @param callback
* @param params
*/
private void _postAsyn(String url, final StringCallback callback, Param... params)
{
Request request = buildPostRequest(url, params);
deliveryResult(callback, request);
} /**
* 异步的post请求
*
* @param url
* @param callback
* @param params
*/
private void _postAsyn(String url, final StringCallback callback, Map<String, String> params)
{
Param[] paramsArr = map2Params(params);
Request request = buildPostRequest(url, paramsArr);
deliveryResult(callback, request);
} /**
* 同步基于post的文件上传
*
* @param params
* @return
*/
private Response _post(String url, File[] files, String[] fileKeys, Param... params) throws IOException
{
Request request = buildMultipartFormRequest(url, files, fileKeys, params);
return mOkHttpClient.newCall(request).execute();
} private Response _post(String url, File file, String fileKey) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
return mOkHttpClient.newCall(request).execute();
} private Response _post(String url, File file, String fileKey, Param... params) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
return mOkHttpClient.newCall(request).execute();
} /**
* 异步基于post的文件上传
*
* @param url
* @param callback
* @param files
* @param fileKeys
* @throws IOException
*/
private void _postAsyn(String url, StringCallback callback, File[] files, String[] fileKeys, Param... params) throws IOException
{
Request request = buildMultipartFormRequest(url, files, fileKeys, params);
deliveryResult(callback, request);
} /**
* 异步基于post的文件上传,单文件不带参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @throws IOException
*/
private void _postAsyn(String url, StringCallback callback, File file, String fileKey) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
deliveryResult(callback, request);
} /**
* 异步基于post的文件上传,单文件且携带其他form参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @param params
* @throws IOException
*/
private void _postAsyn(String url, StringCallback callback, File file, String fileKey, Param... params) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
deliveryResult(callback, request);
} /**
* 异步下载文件
*
* @param url
* @param destFileDir 本地文件存储的文件夹
* @param callback
*/
private void _downloadAsyn(final String url, final String destFileDir, final StringCallback callback)
{
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(final Request request, final IOException e)
{
sendFailedStringCallback(request, e, callback);
} @Override
public void onResponse(Response response)
{
InputStream is = null;
byte[] buf = new byte[];
int len = ;
FileOutputStream fos = null;
try
{
is = response.body().byteStream();
File file = new File(destFileDir, getFileName(url));
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -)
{
fos.write(buf, , len);
}
fos.flush();
//如果下载文件成功,第一个参数为文件的绝对路径
sendSuccessStringCallback(file.getAbsolutePath(), callback);
} catch (IOException e)
{
sendFailedStringCallback(response.request(), e, callback);
} finally
{
try
{
if (is != null) is.close();
} catch (IOException e)
{
}
try
{
if (fos != null) fos.close();
} catch (IOException e)
{
}
} }
});
} private String getFileName(String path)
{
int separatorIndex = path.lastIndexOf("/");
return (separatorIndex < ) ? path : path.substring(separatorIndex + , path.length());
} /**
* 加载图片
*
* @param view
* @param url
* @throws IOException
*/
private void _displayImage(final ImageView view, final String url, final int errorResId)
{
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Request request, IOException e)
{
setErrorResId(view, errorResId);
} @Override
public void onResponse(Response response)
{
InputStream is = null;
try
{
is = response.body().byteStream();
ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);
ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(view);
int inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);
try
{
is.reset();
} catch (IOException e)
{
response = _getAsyn(url);
is = response.body().byteStream();
} BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inJustDecodeBounds = false;
ops.inSampleSize = inSampleSize;
final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
mDelivery.post(new Runnable()
{
@Override
public void run()
{
view.setImageBitmap(bm);
}
});
} catch (Exception e)
{
setErrorResId(view, errorResId); } finally
{
if (is != null) try
{
is.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}); } private void setErrorResId(final ImageView view, final int errorResId)
{
mDelivery.post(new Runnable()
{
@Override
public void run()
{
view.setImageResource(errorResId);
}
});
} //*************对外公布的方法************ public static Response getAsyn(String url) throws IOException
{
return getInstance()._getAsyn(url);
} public static String getAsString(String url) throws IOException
{
return getInstance()._getAsString(url);
} public static void getAsyn(String url, StringCallback callback)
{
getInstance()._getAsyn(url, callback);
} public static Response post(String url, Param... params) throws IOException
{
return getInstance()._post(url, params);
} public static String postAsString(String url, Param... params) throws IOException
{
return getInstance()._postAsString(url, params);
} public static void postAsyn(String url, final StringCallback callback, Param... params)
{
getInstance()._postAsyn(url, callback, params);
} public static void postAsyn(String url, final StringCallback callback, Map<String, String> params)
{
getInstance()._postAsyn(url, callback, params);
} public static Response post(String url, File[] files, String[] fileKeys, Param... params) throws IOException
{
return getInstance()._post(url, files, fileKeys, params);
} public static Response post(String url, File file, String fileKey) throws IOException
{
return getInstance()._post(url, file, fileKey);
} public static Response post(String url, File file, String fileKey, Param... params) throws IOException
{
return getInstance()._post(url, file, fileKey, params);
} public static void postAsyn(String url, StringCallback callback, File[] files, String[] fileKeys, Param... params) throws IOException
{
getInstance()._postAsyn(url, callback, files, fileKeys, params);
} public static void postAsyn(String url, StringCallback callback, File file, String fileKey) throws IOException
{
getInstance()._postAsyn(url, callback, file, fileKey);
} public static void postAsyn(String url, StringCallback callback, File file, String fileKey, Param... params) throws IOException
{
getInstance()._postAsyn(url, callback, file, fileKey, params);
} public static void displayImage(final ImageView view, String url, int errorResId) throws IOException
{
getInstance()._displayImage(view, url, errorResId);
} public static void displayImage(final ImageView view, String url)
{
getInstance()._displayImage(view, url, -);
} public static void downloadAsyn(String url, String destDir, StringCallback callback)
{
getInstance()._downloadAsyn(url, destDir, callback);
} //**************************** private Request buildMultipartFormRequest(String url, File[] files,
String[] fileKeys, Param[] params)
{
params = validateParam(params); MultipartBuilder builder = new MultipartBuilder()
.type(MultipartBuilder.FORM); for (Param param : params)
{
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
RequestBody.create(null, param.value));
}
if (files != null)
{
RequestBody fileBody = null;
for (int i = ; i < files.length; i++)
{
File file = files[i];
String fileName = file.getName();
fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentType
builder.addPart(Headers.of("Content-Disposition",
"form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
fileBody);
}
} RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
} private String guessMimeType(String path)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(path);
if (contentTypeFor == null)
{
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
} private Param[] validateParam(Param[] params)
{
if (params == null)
return new Param[];
else return params;
} private Param[] map2Params(Map<String, String> params)
{
if (params == null) return new Param[];
int size = params.size();
Param[] res = new Param[size];
Set<Map.Entry<String, String>> entries = params.entrySet();
int i = ;
for (Map.Entry<String, String> entry : entries)
{
res[i++] = new Param(entry.getKey(), entry.getValue());
}
return res;
} private void deliveryResult(final StringCallback callback, Request request)
{
mOkHttpClient.newCall(request).enqueue(new Callback()
{
@Override
public void onFailure(final Request request, final IOException e)
{
sendFailedStringCallback(request, e, callback);
} @Override
public void onResponse(final Response response)
{
try
{
final String string = response.body().string();
sendSuccessStringCallback(string, callback);
} catch (IOException e)
{
sendFailedStringCallback(response.request(), e, callback);
} }
});
} private void sendFailedStringCallback(final Request request, final IOException e, final StringCallback callback)
{
mDelivery.post(new Runnable()
{
@Override
public void run()
{
if (callback != null)
callback.onFailure(request, e);
}
});
} private void sendSuccessStringCallback(final String string, final StringCallback callback)
{
mDelivery.post(new Runnable()
{
@Override
public void run()
{
if (callback != null)
callback.onResponse(string);
}
});
} private Request buildPostRequest(String url, Param[] params)
{
if (params == null)
{
params = new Param[];
}
FormEncodingBuilder builder = new FormEncodingBuilder();
for (Param param : params)
{
builder.add(param.key, param.value);
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
} public interface StringCallback
{
void onFailure(Request request, IOException e); void onResponse(String response);
} public static class Param
{
public Param()
{
} public Param(String key, String value)
{
this.key = key;
this.value = value;
} String key;
String value;
} }
Http Get
OkHttpClientManager.getAsyn("https://github.com/hongyangAndroid", new OkHttpClientManager.StringCallback()
{
@Override
public void onFailure(Request request, IOException e)
{
e.printStackTrace();
} @Override
public void onResponse(String bytes)
{
mTv.setText(bytes);//注意这里是UI线程回调,可以直接操作控件
}
});
文件上传且携带参数
OkHttpClientManager.postAsyn("http://192.168.1.103:8080/okHttpServer/fileUpload",//
new OkHttpClientManager.StringCallback()
{
@Override
public void onFailure(Request request, IOException e)
{
e.printStackTrace();
} @Override
public void onResponse(String result)
{ }
},//
file,//
"mFile",//
new OkHttpClientManager.Param[]{
new OkHttpClientManager.Param("username", "zhy"),
new OkHttpClientManager.Param("password", "")}
);
键值对没什么说的,参数3为file,参数4为file对应的name,这个name不是文件的名字;
对应于http中的
<input type="file" name="mFile" >
对应的是name后面的值,即mFile.
文件下载
对于文件下载,提供url,目标dir,callback即可。
OkHttpClientManager.downloadAsyn(
"http://192.168.1.103:8080/okHttpServer/files/messenger_01.png",
Environment.getExternalStorageDirectory().getAbsolutePath(),
new OkHttpClientManager.StringCallback()
{
@Override
public void onFailure(Request request, IOException e)
{ } @Override
public void onResponse(String response)
{
//文件下载成功,这里回调的reponse为文件的absolutePath
}
});
展示图片
展示图片,我们希望提供一个url和一个imageview,如果下载成功,直接帮我们设置上即可。
OkHttpClientManager.displayImage(mImageView, "http://images.csdn.net/20150817/1.jpg");
内部会自动根据imageview的大小自动对图片进行合适的压缩。虽然,这里可能不适合一次性加载大量图片的场景,但是对于app中偶尔有几个图片的加载,还是可用的。
Android OkHttp完全解析 是时候来了解OkHttp了
okHttp封装使用的更多相关文章
- okhttp封装时,提示 cannot resolve method OkHttpClient setConnectTimeout() 函数
如标题所示,okhttp封装时,提示 cannot resolve method OkHttpClient setConnectTimeout() 函数,有遇到这样现象的朋友吗? 原因:因使用的是 ...
- okhttputils【 Android 一个改善的okHttp封装库】使用(一)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 本文使用的OKHttp封装库是张鸿洋(鸿神)写的,因为在项目中一直使用这个库,所以对于一些常用的请求方式都验证过,所以特此整理下. ...
- okhttputils【 Android 一个改善的okHttp封装库】使用(三)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这一篇主要讲一下将OkHttpUtils运用到mvp模式中. 数据请求地址:http://www.wanandroid.com/to ...
- volley+okhttp封装,一行代码就可访问网络
volley+okhttp封装,一行代码就可访问网络 前言: 我写这个可能不会完全的教会你去怎么封装一个网络框架,我的目的在于让你不需要你自己封装就可以访问网络,或者说互相学习也可以,我只是想让你大概 ...
- Android 一个改进的okHttp封装库
一.概述 之前写了篇Android OkHttp完全解析 是时候来了解OkHttp了,其实主要是作为okhttp的普及文章,当然里面也简单封装了工具类,没想到关注和使用的人还挺多的,由于这股热情,该工 ...
- Android 一个改善的okHttp封装库
膜拜一下~ 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/49734867: 本文出自:[张鸿洋的博客] 一.概述 之前写了篇A ...
- 超简单的okhttp封装工具类(上)
版权声明:转载请注明出处:http://blog.csdn.net/piaomiao8179 https://blog.csdn.net/piaomiao8179/article/details/ ...
- OkHttp封装之后使用
代码都封装好了,上层Activity如何调用呢? 1.依赖 如果是android studio开发支持在线依赖(我已经把项目添加到jcenter上): compile 'com.ansen.http: ...
- Okhttp封装、网络层扩展
一.概述 首先在这里本片文章是以网络通信封装为主,而app开发首先重要就是网络通信,而如今主流的async.volley.okhttp等,阿么这么网络库怎样能做到更好封装.更好的切换,从而不影响业务层 ...
- okhttp封装
对这玩意并不熟,网上有很多大神封装好的,但是懒得看里面的封装逻辑,索性自己简单做个封装,方便使用,出现bug也好查找: get请求: /** * get请求 * @param url * @param ...
随机推荐
- QQ与我联系
第一种 <a href=" http://sighttp.qq.com/cgi-bin/check?sigkey=ee8bdb91c04a9ae912a305a5a2461a0d8d6 ...
- Android Studio apk 打包流程
1.Build -> Generate Signed APK...,打开如下窗口 2.假设这里没有打过apk包,点击Create new,窗口如下 这里只要输入几个必要项 Key store p ...
- Eclispse 换主题、皮肤、配色,换黑色主题护眼
链接地址:http://jingyan.baidu.com/article/6c67b1d68c03be2787bb1ed6.html Eclipse写android代码时,默认的文本和框架都是白色, ...
- 用U盘与移动硬盘制作WIN7启动盘(亲自实践)
昨晚帮一个娃娃用移动硬盘里面的一个分区帮他制作成一个win7系统盘,为了以后万一换系统的时候方便.我自己有一个U盘坐的启动盘,移动硬盘没有倒腾过,看网上N多都是相互抄,制作都是WINPE系统的,相当蛋 ...
- 深入windows的关机消息截获-从XP到Win7的变化
之前写了一个软件用于实验室的打卡提醒,其中一个重要的功能是在关机之前提醒当天晚上是否已经打卡.之前我是在WM_ENDSESSION中弹出一个模态对话框来提醒,在XP中基本工作正常,在Win7中大多数时 ...
- IntelliJ IDEA 开发swing(二)
原文:idea开发swing(二) 闲话少说,书接idea开发swing(一). 程序编译完成后,需要打包发布,如果有fat_jar的同学可以通过该插件打包,这里是使用ant来打包,步骤如下: 一.编 ...
- Java__jar包的简单操作
工作需要研究了下jar,这里就举个简单的例子,以helloworld为例吧 1.启动eclipse编写代码: 次步不做赘述 package cn.test.jar; public class Hell ...
- 关于如何实现程序一天只启动一次的想法(C++实现)
问题描述: 我们在程序开发当中,经常会遇到某些子程序需要实现一天只启动一次的功能,该功能实现的方法有很多种,其原理都是通过记录标记为来实现的.本次要分享的也是利用程序标记为来实现的,而且只需要使用一个 ...
- JQuery Datatable Ajax请求两次问题的解决
最近一个项目中使用JQuery Datatable,用起来比较方便,但在测试过程中,发现当条件改变时,有时查询结果中的数据不正确. 使用FireBug跟踪时,发现在使用Ajax请求时,点击一次搜索按钮 ...
- Android-x86 4.4-r5 发布,PC 上的安卓系统
Android x86 即运行于 x86 PC上的Android操作系统,目前已经支持大部分安卓程序. Android X86平台是由Beyounn和Cwhuang主持设计的.项目的主要目的在于为X8 ...