import com.zhy.http.okhttp.OkHttpUtils; //导入方法依赖的package包/类
@Override
public void performRequestAsync(AyoRequest request, BaseResponseDispatcher responseHandler, BaseHttpCallback callback) {
String url = request.url;
//基于OkHttpUtils辅助类
//1 method决定了OkHttpRequestBuilder的哪个子类
if(request.method.equalsIgnoreCase("get")){
OkHttpUtils
.get()
.headers(request.headers)
.url(url)
.tag(request.flag)
.build()
.execute(new MyStringCallback(request, responseHandler, callback));
}else if(request.method.equalsIgnoreCase("post")){
boolean hasStringEntity = (request.stringEntity != null && !request.stringEntity.equals(""));
boolean postFileLikeForm = (request.files != null && request.files.size() > 0);
boolean postFileLikeStream = (request.file != null);
//情况1:postForm
if(!hasStringEntity && !postFileLikeForm && !postFileLikeStream){
OkHttpUtils
.post()//
.url(url)
.headers(request.headers)
.params(request.params)
.tag(request.flag)
.build()
.execute(new MyStringCallback(request, responseHandler, callback));
}
//情况2:postString
//情况3:postFile--流形式,不带name,带mime
//情况4:postFile--表单形式,带name,带filename
if(hasStringEntity){
OkHttpUtils
.postString()
.url(url)
.headers(request.headers)
.mediaType(MediaType.parse("application/json; charset=utf-8"))
.content(request.stringEntity)
.tag(request.flag)
.build()
.execute(new MyStringCallback(request, responseHandler, callback));
}else if(postFileLikeStream){
OkHttpUtils
.postFile()
.url(url)
.headers(request.headers)//
.file(request.file)
.build()
.execute(new MyStringCallback(request, responseHandler, callback));
}else if(postFileLikeForm){
PostFormBuilder b = OkHttpUtils.post();
for(String key: request.files.keySet()){
File f = request.files.get(key);
b.addFile(key, f.getName(), f);
}
b.url(url)//
.params(request.params)//
.headers(request.headers)//
.build()//
.execute(new MyStringCallback(request, responseHandler, callback));
}
}else{
throw new RuntimeException("使用了不支持的http谓词:" + request.method);
}
}