OkHttp:网络请求(第三方):
接口回调加封装:
log拦截器在tokend的后面
get和post (接口) :
public interface MyOkListener {
void onError(String mesage);//返回错误信息
void onSuccess(String json);//返回数据
}
下载(接口) :
public interface MyFileListener {
void setMax(int max);//设置最大值
void setProgress(int progress);//设置当前进度
void onFinish();//下载完成
void onError(String message);//错误
}
modle:
public interface OkHttpModel {
void get(String str_url,MyOkListener listener);
void post(String str_url, HashMap<String,String> map,MyOkListener listener);
void download(String str_url,String path,MyFileListener listener);
void upload(String str_url,String path,String filename,String type,MyFileListener listener);
}
实现类:
public class OkHttpModelIpml implements OkHttpModel {
@Override
public void get(String str_url, MyOkListener listener) {
OkhttpUtils.getInstance().doget(str_url,listener);
}
@Override
public void post(String str_url, HashMap<String, String> map, MyOkListener listener) {
OkhttpUtils.getInstance().dopost(str_url,map,listener);
}
@Override
public void download(String str_url, String path, MyFileListener listener) {
OkhttpUtils.getInstance().download(str_url,path,listener);
}
@Override
public void upload(String str_url, String path, String filename, String type,MyFileListener listener) {
OkhttpUtils.getInstance().upload(str_url,path,filename,type,listener);
}
}
工具类 :(单例 拦截器 )
public class OkhttpUtils {
private OkHttpClient okHttpClient;//在构造方法里面创建
//单例模式:构造私有化
private OkhttpUtils(){//只会创建一次
//log拦截器
HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//token拦截器
Interceptor tokenInterceptor=new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();//获得request对象
// Request.Builder builder = request.newBuilder();//通过request获得builder
// builder.header("token","1705B");//设置请求头
// Request request1 = builder.build();//添加了token的request
Request request1=chain.request().newBuilder().header("token","1705B").build();
return chain.proceed(request1);
}
};
okHttpClient=new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.addInterceptor(tokenInterceptor)//添加token拦截器,一定要在log拦截器之前设置
.addInterceptor(httpLoggingInterceptor)//添加log拦截器
.build();
};
//自行实例化
private static OkhttpUtils okhttpUtils=null;
//公开方法
public static OkhttpUtils getInstance(){
//双重校验锁:
if(okhttpUtils==null){
synchronized (StringBuilder.class){
if(okhttpUtils==null){
okhttpUtils=new OkhttpUtils();
}
}
}
return okhttpUtils;
}
/***
* @param str_url 网址
* @param listener 回调 将请求的结果返回给Activitt
*/
public void doget(String str_url, final MyOkListener listener){
//TODO 2:request对象
Request request=new Request.Builder().url(str_url).get().header("Connection","Keep-Alive").build();
//TODO 3:call
Call call = okHttpClient.newCall(request);
//TODO 4:加入队列 得到response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
listener.onSuccess(response.body().string());
}
});
}
/***
*
* @param str_url 请求网址
* @param listener 回调的监听
* @param map 请求体参数
*/
public void dopost(String str_url, HashMap<String,String> map, final MyOkListener listener){
//TODO 请求体
FormBody.Builder builder1 = new FormBody.Builder();
Set<Map.Entry<String, String>> entries = map.entrySet();//键值对的集合
for (Map.Entry<String, String> entry : entries) {//遍历集合
String key = entry.getKey();//获得键
String value = entry.getValue();//获得值
builder1.add(key,value);
}
FormBody formBody = builder1.build();
//TODO 2:request对象
Request request = new Request.Builder().url(str_url).post(formBody).build();
//TODO 3:call
Call call = okHttpClient.newCall(request);
//TODO 4:加入队列 得到response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
listener.onSuccess(response.body().string());
}
});
}
/***
* @param str_url 网址
* @param path 下载地址
* @param listener 监听
*/
public void download(String str_url, final String path, final MyFileListener listener){
//TODO 1:request对象
Request request = new Request.Builder()
.url(str_url)
.get()
.build();
//TODO 2:客户端发起连接得到call
Call call = okHttpClient.newCall(request);
//TODO 3:加入队列得到response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
//TODO 1:获得总长度
long max = body.contentLength();
listener.setMax((int) max);//返回最大值
//TODO 2:得到输入流
InputStream inputStream = body.byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(path);
byte[] bytes=new byte[1024];
int len=0;
int count=0;
while((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
count+=len;
listener.setProgress(count);//通知进度
}
listener.onFinish();//通知完成
}
});
}
/****
*
* @param str_url 请求网址
* @param path 上传文件的路径
* @param filename 上传到服务器那边生成文件的名称
* @param type 类型
* @param listener 监听
*/
public void upload(String str_url, String path, String filename,String type, final MyFileListener listener){
//请求体如何设置
MultipartBody body=new MultipartBody.Builder()
.setType(MultipartBody.FORM)//设置方式
.addFormDataPart("file",filename, RequestBody.create(MediaType.parse(type),new File(path)))
.build();
//---------------------
Request request=new Request.Builder().url(str_url).post(body).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
listener.onFinish();
}
});
}
}