public class OkHttpManager {
private static OkHttpClient mOkHttpClient;
private static volatile OkHttpManager instance = null;
private OkHttpManager() {
}
public static OkHttpManager getInstance() {
if (mOkHttpClient == null) {
if (instance == null) {
synchronized (OkHttpManager.class) {
if (mOkHttpClient == null)
mOkHttpClient = new OkHttpClient();
if (instance == null)
instance = new OkHttpManager();
initOkHttpClient();
}
}
}
return instance;
}
/**
* 设置请求超时时间以及缓存
*/
private static void initOkHttpClient() {
//设置缓存目录
File sdcache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cache");
//设置缓存大小,10MB
int cacheSize = 1024 * 1024 * 10;
OkHttpClient.Builder builder = new OkHttpClient.Builder()
//连接超时时间 10S
.connectTimeout(10, TimeUnit.SECONDS)
//写入超时时间 20S
.writeTimeout(20, TimeUnit.SECONDS)
//读取超时时间 20S
.readTimeout(20, TimeUnit.SECONDS)
//缓存
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
//将请求设置参数赋值给OkHttp对象
mOkHttpClient = builder.build();
}
/**
* get异步请求
*
* @param what 唯一识别码
* @param httpCallBack 回调
* @param httpUrl 请求地址
*/
public void getAsynHttp(final int what, final HttpCallBack httpCallBack, final String httpUrl) {
Request requestBuilder = new Request.Builder()
.url(httpUrl)
.method("GET", null)
.build();
Call mcall = mOkHttpClient.newCall(requestBuilder);
mcall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpCallBack.onResponse(what, response.body().string());
}
});
}
/**
* get同步请求
*
* @param what 唯一识别码
* @param httpUrl 请求地址
*/
public void getSyncHttp(final int what, final String httpUrl) {
Request builder = new Request.Builder()
.url(httpUrl)
.method("GET", null)
.build();
Call call = mOkHttpClient.newCall(builder);
try {
Response response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* post同步请求
*
* @param what 唯一识别码
* @param httpUrl 请求地址
*/
public void postSyncHttp(final int what, final String httpUrl) {
Request builder = new Request.Builder()
.url(httpUrl)
.method("POST", null)
.build();
Call call = mOkHttpClient.newCall(builder);
try {
Response response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* post异步提交键值对
*
* @param what 唯一识别码
* @param httpCallBack 回调
* @param httpUrl 请求地址
* @param stringMap map数组
*/
public void postAsynHttp(final int what, final HttpCallBack httpCallBack, final String httpUrl, final Map<String, String> stringMap) {
FormBody.Builder formBody = new FormBody.Builder();
for (String key : stringMap.keySet()) {
formBody.add(key, stringMap.get(key));
}
Request request = new Request.Builder()
.url(httpUrl)
.post(formBody.build())
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpCallBack.onResponse(what, response.body().string());
}
});
}
/**
* 异步上传文件
* @param what 唯一识别码
* @param httpCallBack 回调
* @param httpUrl 上传地址
* @param filapath 本地地址
*/
public void uploadAsynFile(final int what,final HttpCallBack httpCallBack,final String httpUrl,String filapath){
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), filapath);
Request request = new Request.Builder()
.post(requestBody)
.url(httpUrl)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpCallBack.onResponse(what, response.body().string());
}
});
}
/**
* 异步下载文件
*
* @param what 唯一识别码
* @param httpCallBack 回调
* @param httpFilePath 请求地址
* @param filePath 本地地址
*/
public void downAsynFile(final int what, final HttpCallBack httpCallBack, final String httpFilePath, final String filePath) {
Request request = new Request.Builder()
.url(httpFilePath)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) {
//拿到字节流
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(filePath));
byte[] bytes = new byte[1024 * 1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
fileOutputStream.flush();
httpCallBack.onResponse(what, "下载成功");
} catch (IOException e) {
e.printStackTrace();
httpCallBack.onResponse(what, "下载异常:" + e.toString());
}
}
});
}
public interface HttpCallBack {
/**
* 请求成功回调接口
*/
void onResponse(int what, String response);
/**
* 请求失败回调接口
*/
void onFailure(int what, String error);
}
}
使用方法:
HashMap<String, String> map = new HashMap<>();
OkHttpManager.getInstance().postAsynHttp(200, new OkHttpManager.HttpCallBack() {
@Override
public void onResponse(int what, String response) {
}
@Override
public void onFailure(int what, String error) {
}
},"ur;",map);
}
或者:
HashMap<String, String> map = new HashMap<>();
//使MainActivity继承OkHttpManager.HttpCallBack,重写方法
OkHttpManager.getInstance().postAsynHttp(201,MainActivity.this,"url",map);
@Override
public void onResponse(int what, String response) {
}
@Override
public void onFailure(int what, String error) {
}