use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.
the class DownUpLoadHelper method downloadingFile.
/**
* 开始文件下载
*/
HttpInfo downloadingFile(OkHttpHelper okHttpInfo, Response res, Call call) {
final HttpInfo info = httpInfo;
final DownloadFileInfo fileInfo = okHttpInfo.getDownloadFileInfo();
RandomAccessFile accessFile = null;
InputStream inputStream = null;
BufferedInputStream bis = null;
String filePath = fileInfo.getSaveFileDir() + fileInfo.getSaveFileNameWithExtension();
try {
ResponseBody responseBody = res.body();
int length;
long completedSize = fileInfo.getCompletedSize();
accessFile = new RandomAccessFile(fileInfo.getSaveFileDir() + fileInfo.getSaveFileNameEncrypt(), "rwd");
//服务器不支持断点下载时重新下载
if (TextUtils.isEmpty(res.header("Content-Range"))) {
completedSize = 0L;
fileInfo.setCompletedSize(completedSize);
}
accessFile.seek(completedSize);
inputStream = responseBody.byteStream();
byte[] buffer = new byte[2048];
bis = new BufferedInputStream(inputStream);
fileInfo.setDownloadStatus(DownloadStatus.DOWNLOADING);
while ((length = bis.read(buffer)) > 0 && (DownloadStatus.DOWNLOADING.equals(fileInfo.getDownloadStatus()))) {
accessFile.write(buffer, 0, length);
completedSize += length;
}
if (DownloadStatus.PAUSE.equals(fileInfo.getDownloadStatus())) {
return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.Message, "暂停下载");
}
//下载完成
if (DownloadStatus.DOWNLOADING.equals(fileInfo.getDownloadStatus())) {
fileInfo.setDownloadStatus(DownloadStatus.COMPLETED);
File newFile = new File(fileInfo.getSaveFileDir(), fileInfo.getSaveFileNameWithExtension());
//处理文件已存在逻辑
if (newFile.exists() && newFile.isFile()) {
filePath = fileInfo.getSaveFileDir() + fileInfo.getSaveFileNameCopy();
newFile = new File(fileInfo.getSaveFileDir(), fileInfo.getSaveFileNameCopy());
}
File oldFile = new File(fileInfo.getSaveFileDir(), fileInfo.getSaveFileNameEncrypt());
if (oldFile.exists() && oldFile.isFile()) {
boolean rename = oldFile.renameTo(newFile);
showLog("重命名[" + rename + "]:" + newFile.getAbsolutePath());
}
return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.SUCCESS, filePath);
}
} catch (SocketTimeoutException e) {
return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.WriteAndReadTimeOut);
} catch (SocketException e) {
return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.ConnectionInterruption, e.getMessage());
} catch (Exception e) {
showLog("文件下载异常:" + e.getMessage());
return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.ConnectionInterruption);
} finally {
try {
if (null != bis)
bis.close();
if (null != inputStream)
inputStream.close();
if (null != accessFile)
accessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
BaseActivityLifecycleCallbacks.cancel(requestTag, call);
//删除下载任务
if (null != downloadTaskMap)
downloadTaskMap.remove(fileInfo.getSaveFileNameEncrypt());
}
return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.SUCCESS, filePath);
}
use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.
the class DownUpLoadHelper method uploadFile.
/**
* 文件上传
*/
void uploadFile(OkHttpHelper helper) {
try {
final HttpInfo info = httpInfo;
List<UploadFileInfo> uploadFileList = helper.getUploadFileInfoList();
String url = info.getUrl();
if (TextUtils.isEmpty(url)) {
showLog("文件上传接口地址不能为空");
return;
}
StringBuilder log = new StringBuilder("PostParams: ");
MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
ProgressCallback progressCallback = helper.getProgressCallback();
String logInfo;
if (null != info.getParams() && !info.getParams().isEmpty()) {
for (String key : info.getParams().keySet()) {
mBuilder.addFormDataPart(key, info.getParams().get(key));
logInfo = key + " =" + info.getParams().get(key) + ", ";
log.append(logInfo);
}
}
for (UploadFileInfo fileInfo : uploadFileList) {
if (progressCallback == null) {
progressCallback = fileInfo.getProgressCallback();
}
String filePath = fileInfo.getFilePathWithName();
String interfaceParamName = fileInfo.getInterfaceParamName();
File file = new File(filePath);
log.append(interfaceParamName);
log.append("=");
log.append(filePath);
log.append(",");
mBuilder.addFormDataPart(interfaceParamName, file.getName(), RequestBody.create(MediaTypeUtil.fetchFileMediaType(filePath), file));
}
showLog(log.toString());
RequestBody requestBody = mBuilder.build();
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url).post(new ProgressRequestBody(requestBody, progressCallback, timeStamp, requestTag));
helper.getHttpHelper().addHeadsToRequest(info, requestBuilder);
Request request = requestBuilder.build();
helper.setRequest(request);
helper.getHttpHelper().responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_UPLOAD_CALLBACK, requestTag);
} catch (Exception e) {
showLog("上传文件失败:" + e.getMessage());
}
}
use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.
the class HttpHelper method doRequestSync.
/**
* 同步请求
*/
HttpInfo doRequestSync(OkHttpHelper helper) {
Call call = null;
final HttpInfo info = httpInfo;
Request request = helper.getRequest();
String url = info.getUrl();
if (!checkUrl(url)) {
return retInfo(info, HttpInfo.CheckURL);
}
request = request == null ? buildRequest(info, helper.getRequestMethod(), helper.getProgressCallback()) : request;
showUrlLog(request);
helper.setRequest(request);
OkHttpClient httpClient = helper.getHttpClient();
try {
httpClient = httpClient == null ? super.httpClient : httpClient;
call = httpClient.newCall(request);
BaseActivityLifecycleCallbacks.putCall(requestTag, call);
Response res = call.execute();
return dealResponse(helper, res, call);
} catch (IllegalArgumentException e) {
return retInfo(info, HttpInfo.ProtocolException);
} catch (SocketTimeoutException e) {
if (null != e.getMessage()) {
if (e.getMessage().contains("failed to connect to"))
return retInfo(info, ConnectionTimeOut);
if (e.getMessage().equals("timeout"))
return retInfo(info, WriteAndReadTimeOut);
}
return retInfo(info, WriteAndReadTimeOut);
} catch (UnknownHostException e) {
if (!helperInfo.getOkHttpUtil().isNetworkAvailable()) {
return retInfo(info, HttpInfo.CheckNet, "[" + e.getMessage() + "]");
} else {
return retInfo(info, HttpInfo.CheckURL, "[" + e.getMessage() + "]");
}
} catch (NetworkOnMainThreadException e) {
return retInfo(info, HttpInfo.NetworkOnMainThreadException);
} catch (Exception e) {
return retInfo(info, HttpInfo.NoResult, "[" + e.getMessage() + "]");
} finally {
BaseActivityLifecycleCallbacks.cancel(requestTag, call);
}
}
use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.
the class HttpHelper method dealResponse.
/**
* 处理HTTP响应
*/
private HttpInfo dealResponse(OkHttpHelper helper, Response res, Call call) {
showLog(String.format(Locale.getDefault(), "CostTime: %.3fs", (System.nanoTime() - startTime) / 1e9d));
final HttpInfo info = httpInfo;
BufferedReader bufferedReader = null;
String result = "";
try {
if (null != res) {
final int netCode = res.code();
if (res.isSuccessful()) {
if (helper.getBusinessType() == BusinessType.HttpOrHttps || helper.getBusinessType() == BusinessType.UploadFile) {
//服务器响应编码格式
String encoding = info.getResponseEncoding();
if (TextUtils.isEmpty(encoding)) {
encoding = helper.getResponseEncoding();
}
bufferedReader = new BufferedReader(new InputStreamReader(res.body().byteStream(), encoding));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
return retInfo(info, netCode, HttpInfo.SUCCESS, result);
} else if (helper.getBusinessType() == BusinessType.DownloadFile) {
//下载文件
return helper.getDownUpLoadHelper().downloadingFile(helper, res, call);
}
} else {
showLog("HttpStatus: " + netCode);
if (netCode == 400) {
return retInfo(info, netCode, HttpInfo.RequestParamError);
} else if (netCode == 404) {
//请求页面路径错误
return retInfo(info, netCode, HttpInfo.ServerNotFound);
} else if (netCode == 416) {
//请求数据流范围错误
return retInfo(info, netCode, HttpInfo.Message, "请求Http数据流范围错误\n" + result);
} else if (netCode == 500) {
//服务器内部错误
return retInfo(info, netCode, HttpInfo.NoResult);
} else if (netCode == 502) {
//错误的网关
return retInfo(info, netCode, HttpInfo.GatewayBad);
} else if (netCode == 504) {
//网关超时
return retInfo(info, netCode, HttpInfo.GatewayTimeOut);
} else {
return retInfo(info, netCode, HttpInfo.CheckNet);
}
}
}
return retInfo(info, HttpInfo.CheckURL);
} catch (Exception e) {
return retInfo(info, HttpInfo.NoResult, "[" + e.getMessage() + "]");
} finally {
if (null != res) {
res.close();
}
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.
the class DownloadActivity method downloadFile.
private void downloadFile() {
final HttpInfo info = HttpInfo.Builder().addDownloadFile(fileURL, "myMP4", new ProgressCallback() {
@Override
public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
downloadProgress.setProgress(percent);
tvResult.setText(percent + "%");
LogUtil.d(TAG, "下载进度:" + percent);
}
@Override
public void onResponseMain(String filePath, HttpInfo info) {
tvResult.setText(info.getRetDetail());
LogUtil.d(TAG, "下载结果:" + info.getRetDetail());
}
}).build();
OkHttpUtil.Builder().setReadTimeout(120).build(//绑定请求标识
requestTag).doDownloadFileAsync(info);
}
Aggregations