参考链接:https://blog.csdn.net/fxjzzyo/article/details/78761373?utm_source=blogxgwz1
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
同步请求:
需要自己处理,UI异步的更新,以及Thread的创建
package com.liboshuai.framework.manager;
import android.content.Context;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* FileName: HttpManager
* Founder: Boshuai.li
* Profile: OkHttp
*/
public class HttpManager {
private static final String HEAD_CONTENT_TYPE = "Content-Type";
private static final String CONTENT_TYPE_JSON = "application/json; charset=utf-8";
// 与服务端定好协议
public static String HEAD_TIMESTAMP = "timestamp";
private static volatile HttpManager mInstnce = null;
private OkHttpClient mOkHttpClient;
private HttpManager() {
mOkHttpClient = new OkHttpClient();
}
public static HttpManager getInstance() {
if (mInstnce == null) {
synchronized (HttpManager.class) {
if (mInstnce == null) {
mInstnce = new HttpManager();
}
}
}
return mInstnce;
}
/**
* 请求网络
*
* @param map
*/
/**
* 请求网络
*
* @param url
* @param context
* @param map 请求参数,GET时为NULL,不为NULL 则POST
* @return
*/
public String startRequest(String url, Context context, HashMap<String, String> map) {
//参数
String timestamp = getTimeStamp() + "";
//参数填充
FormBody.Builder bodyBuilder = null;
if (map != null) {
bodyBuilder = new FormBody.Builder();
for (String key : map.keySet()) {
String value = map.get(key);
if (value != null) {
bodyBuilder.add(key, value);
}
}
}
Request.Builder reqBuilder = new Request.Builder();
// 添加 url 和 头部信息
reqBuilder.url(url)
.addHeader(HEAD_TIMESTAMP, timestamp)
.addHeader(HEAD_CONTENT_TYPE, CONTENT_TYPE_JSON);
// GET or POST
if (bodyBuilder != null) {
RequestBody requestBody = bodyBuilder.build();
reqBuilder.post(requestBody);
} else {
reqBuilder.get();
}
Request request = reqBuilder.build();
try {
return mOkHttpClient.newCall(request).execute().body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取当前时间戳
* 将最后的三位去掉
*
* @return
*/
public long getTimeStamp() {
return System.currentTimeMillis() / 1000;
}
/**
* 下载
*
* @param url
* @param saveDir
* @param listener
*/
public void download(final String url, final String saveDir, final OnDownloadListener listener) {
Request request = new Request.Builder().url(url).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onDownloadFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
//储存下载文件的目录
//String savePath = isExistDir(saveDir);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
//不用从url 直接从path
File file = new File(saveDir);
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
listener.onDownloading(progress);
}
fos.flush();
//下载完成
listener.onDownloadSuccess(file.getAbsolutePath());
} catch (Exception e) {
listener.onDownloadFailed(e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
});
}
/**
* 下载进度监听
*/
public interface OnDownloadListener {
/**
* 下载成功
*/
void onDownloadSuccess(String path);
/**
* 下载进度
*
* @param progress
*/
void onDownloading(int progress);
/**
* 下载失败
*/
void onDownloadFailed(Exception e);
}
}
异步请求:
联合RxJava以及RxAndroid,最大化可读性:
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.squareup.okio:okio:2.1.0'
下面上详细使用代码:
Get请求测试:
/**
* Get 请求测试
*/
public void testOKHttpManager() {
// 需要在onDestroy 时调用 disposable.dispose();
Disposable disposable = Observable.create((ObservableOnSubscribe<String>) emitter -> {
// 获取服务端 响应
String resp = HttpManager.getInstance().startRequest(Consts.URL_BASIC_SERVER, TestActivity.this, null);
emitter.onNext(resp);
emitter.onComplete();
}).subscribeOn(Schedulers.newThread()) // 子线程执行方法
.observeOn(AndroidSchedulers.mainThread()) // 主线程回调
.subscribe(s -> parsingpResp(s));
}
/**
* 解析 服务端返回的数据
* @param respStr
*/
public void parsingpResp(String respStr) {
}
POST请求测试:
/**
* POST 请求测试
*/
public void testOKHttpManager2() {
// 需要在onDestroy 时调用 disposable.dispose();
Disposable disposable = Observable.create((ObservableOnSubscribe<String>) emitter -> {
HashMap<String, String> map = new HashMap<>();
// String 类型
map.put("key1", "value1");
// int类型
int value2 = 3;
map.put("key2", value2 + "");
// 获取服务端 响应
String resp = HttpManager.getInstance().startRequest(Consts.URL_BASIC_SERVER, TestActivity.this, map);
emitter.onNext(resp);
emitter.onComplete();
}).subscribeOn(Schedulers.newThread()) // 子线程执行方法
.observeOn(AndroidSchedulers.mainThread()) // 主线程回调
.subscribe(s -> parsingpResp2(s));
}
/**
* 解析 服务端返回的数据
* @param respStr
*/
public void parsingpResp2(String respStr) {
}