use of com.squareup.okhttp.ResponseBody in project SimplifyReader by chentao0707.
the class OkHttpStack method entityFromOkHttpResponse.
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
BasicHttpEntity entity = new BasicHttpEntity();
ResponseBody body = r.body();
entity.setContent(body.byteStream());
entity.setContentLength(body.contentLength());
entity.setContentEncoding(r.header("Content-Encoding"));
if (body.contentType() != null) {
entity.setContentType(body.contentType().type());
}
return entity;
}
use of com.squareup.okhttp.ResponseBody in project remusic by aa112901.
the class DownloadTask method run.
@Override
public void run() {
Log.e("start", completedSize + "");
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_PREPARE;
// id = (saveDirPath + fileName).hashCode() + "";
onPrepare();
InputStream inputStream = null;
BufferedInputStream bis = null;
try {
dbEntity = downFileStore.getDownLoadedList(id);
file = new RandomAccessFile(saveDirPath + fileName, "rwd");
if (dbEntity != null) {
completedSize = dbEntity.getCompletedSize();
totalSize = dbEntity.getTotalSize();
}
if (file.length() < completedSize) {
completedSize = file.length();
}
long fileLength = file.length();
if (fileLength != 0 && totalSize == fileLength) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_COMPLETED;
totalSize = completedSize = fileLength;
dbEntity = new DownloadDBEntity(id, totalSize, completedSize, url, saveDirPath, fileName, artist, downloadStatus);
downFileStore.insert(dbEntity);
Log.e(TAG, "file is completed , file length = " + fileLength + " file totalsize = " + totalSize);
Toast.makeText(mContext, fileName + "已经下载完成", Toast.LENGTH_SHORT).show();
onCompleted();
return;
} else if (fileLength > totalSize) {
completedSize = 0;
totalSize = 0;
}
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_START;
onStart();
Request request = new Request.Builder().url(url).header("RANGE", // Http value set breakpoints RANGE
"bytes=" + completedSize + "-").addHeader("Referer", url).build();
Log.e("comlesize", completedSize + "");
file.seek(completedSize);
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
if (responseBody != null) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_DOWNLOADING;
if (totalSize <= 0)
totalSize = responseBody.contentLength();
inputStream = responseBody.byteStream();
bis = new BufferedInputStream(inputStream);
byte[] buffer = new byte[4 * 1024];
int length = 0;
int buffOffset = 0;
if (dbEntity == null) {
dbEntity = new DownloadDBEntity(id, totalSize, 0L, url, saveDirPath, fileName, artist, downloadStatus);
downFileStore.insert(dbEntity);
}
while ((length = bis.read(buffer)) > 0 && downloadStatus != DownloadStatus.DOWNLOAD_STATUS_CANCEL && downloadStatus != DownloadStatus.DOWNLOAD_STATUS_PAUSE) {
file.write(buffer, 0, length);
completedSize += length;
buffOffset += length;
if (buffOffset >= UPDATE_SIZE) {
// Update download information database
if (totalSize <= 0 || dbEntity.getTotalSize() <= 0)
dbEntity.setToolSize(totalSize);
buffOffset = 0;
dbEntity.setCompletedSize(completedSize);
dbEntity.setDownloadStatus(downloadStatus);
downFileStore.update(dbEntity);
onDownloading();
}
}
//这两句根据需要自行选择是否注释,注释掉的话由于少了数据库的读取,速度会快一点,但同时如果在下载过程程序崩溃的话,程序不会保存最新的下载进度
dbEntity.setCompletedSize(completedSize);
dbEntity.setDownloadStatus(downloadStatus);
downFileStore.update(dbEntity);
onDownloading();
}
} catch (FileNotFoundException e) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_ERROR;
onError(DownloadTaskListener.DOWNLOAD_ERROR_FILE_NOT_FOUND);
return;
// e.printStackTrace();
} catch (IOException e) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_ERROR;
onError(DownloadTaskListener.DOWNLOAD_ERROR_IO_ERROR);
return;
} finally {
//String nP = fileName.substring(0, path.length() - 5);
dbEntity.setCompletedSize(completedSize);
dbEntity.setFileName(fileName);
downFileStore.update(dbEntity);
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file != null)
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (totalSize == completedSize) {
String path = saveDirPath + fileName;
File file = new File(path);
Log.e("rename", path.substring(0, path.length() - 5));
boolean c = file.renameTo(new File(path + ".mp3"));
Log.e("rename", c + "");
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_COMPLETED;
dbEntity.setDownloadStatus(downloadStatus);
downFileStore.update(dbEntity);
Uri contentUri = Uri.fromFile(new File(saveDirPath + fileName + ".mp3"));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
switch(downloadStatus) {
case DownloadStatus.DOWNLOAD_STATUS_COMPLETED:
onCompleted();
break;
case DownloadStatus.DOWNLOAD_STATUS_PAUSE:
onPause();
break;
case DownloadStatus.DOWNLOAD_STATUS_CANCEL:
downFileStore.deleteTask(dbEntity.getDownloadId());
File temp = new File(saveDirPath + fileName);
if (temp.exists())
temp.delete();
onCancel();
break;
}
}
use of com.squareup.okhttp.ResponseBody in project stetho by facebook.
the class StethoInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
String requestId = mEventReporter.nextRequestId();
Request request = chain.request();
RequestBodyHelper requestBodyHelper = null;
if (mEventReporter.isEnabled()) {
requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request, requestBodyHelper);
mEventReporter.requestWillBeSent(inspectorRequest);
}
Response response;
try {
response = chain.proceed(request);
} catch (IOException e) {
if (mEventReporter.isEnabled()) {
mEventReporter.httpExchangeFailed(requestId, e.toString());
}
throw e;
}
if (mEventReporter.isEnabled()) {
if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
requestBodyHelper.reportDataSent();
}
Connection connection = chain.connection();
mEventReporter.responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));
ResponseBody body = response.body();
MediaType contentType = null;
InputStream responseStream = null;
if (body != null) {
contentType = body.contentType();
responseStream = body.byteStream();
}
responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId));
if (responseStream != null) {
response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
}
}
return response;
}
use of com.squareup.okhttp.ResponseBody in project QuickAndroid by ImKarl.
the class QAFileHttpHandler method handlerResponse.
@Override
public File handlerResponse(Response response) throws Exception {
if (targetFile == null) {
throw new QANoFoundException(QAException.CODE_IO_FILE, "'targetFile'不能为空");
}
File parentFile = targetFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
Exception exception = null;
InputStream stream = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
ResponseBody responseBody = response.body();
stream = responseBody.byteStream();
fos = new FileOutputStream(targetFile);
while ((len = stream.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception e) {
exception = e;
} finally {
try {
if (stream != null)
stream.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
if (exception == null) {
return targetFile;
}
throw new QAIOException(QAException.CODE_IO_FILE, exception);
}
use of com.squareup.okhttp.ResponseBody in project bdcodehelper by boredream.
the class ErrorConstants method parseHttpErrorInfo.
/**
* 解析服务器错误信息
*/
public static String parseHttpErrorInfo(Throwable throwable) {
String errorInfo = throwable.getMessage();
if (throwable instanceof HttpException) {
// 如果是Retrofit的Http错误,则转换类型,获取信息
HttpException exception = (HttpException) throwable;
ResponseBody responseBody = exception.response().errorBody();
MediaType type = responseBody.contentType();
// 如果是application/json类型数据,则解析返回内容
if (type.type().equals("application") && type.subtype().equals("json")) {
try {
// 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
ErrorResponse errorResponse = new Gson().fromJson(responseBody.string(), ErrorResponse.class);
errorInfo = getLocalErrorInfo(errorResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
if (throwable instanceof UnknownHostException) {
errorInfo = "无法连接到服务器";
}
}
return errorInfo;
}
Aggregations