use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.
the class DownloadTask method doInBackground.
/** 一旦该方法执行,意味着开始下载了 */
@Override
protected DownloadInfo doInBackground(Void... params) {
if (isCancelled())
return mDownloadInfo;
mPreviousTime = System.currentTimeMillis();
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.DOWNLOADING);
postMessage(null, null);
long startPos = mDownloadInfo.getDownloadLength();
Response response;
try {
response = mDownloadInfo.getRequest().headers("RANGE", "bytes=" + startPos + "-").execute();
} catch (IOException e) {
e.printStackTrace();
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.ERROR);
postMessage("网络异常", e);
return mDownloadInfo;
}
int code = response.code();
if (code == 404 || code >= 500) {
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.ERROR);
postMessage("服务器数据错误", null);
return mDownloadInfo;
}
//构建下载文件路径,如果有设置,就用设置的,否者就自己创建
String url = mDownloadInfo.getUrl();
String fileName = mDownloadInfo.getFileName();
if (TextUtils.isEmpty(fileName)) {
fileName = HttpUtils.getNetFileName(response, url);
mDownloadInfo.setFileName(fileName);
}
if (TextUtils.isEmpty(mDownloadInfo.getTargetPath())) {
File targetFolder = new File(mDownloadInfo.getTargetFolder());
if (!targetFolder.exists())
targetFolder.mkdirs();
File file = new File(targetFolder, fileName);
mDownloadInfo.setTargetPath(file.getAbsolutePath());
}
//检查文件有效性,文件大小大于总文件大小
if (startPos > mDownloadInfo.getTotalLength()) {
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.ERROR);
postMessage("断点文件异常,需要删除后重新下载", null);
return mDownloadInfo;
}
if (startPos == mDownloadInfo.getTotalLength() && startPos > 0) {
mDownloadInfo.setProgress(1.0f);
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.FINISH);
postMessage(null, null);
return mDownloadInfo;
}
//设置断点写文件
File file = new File(mDownloadInfo.getTargetPath());
ProgressRandomAccessFile randomAccessFile;
try {
randomAccessFile = new ProgressRandomAccessFile(file, "rw", startPos);
randomAccessFile.seek(startPos);
} catch (Exception e) {
e.printStackTrace();
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.ERROR);
postMessage("没有找到已存在的断点文件", e);
return mDownloadInfo;
}
//获取流对象,准备进行读写文件
long totalLength = response.body().contentLength();
if (mDownloadInfo.getTotalLength() == 0) {
mDownloadInfo.setTotalLength(totalLength);
}
InputStream is = response.body().byteStream();
//读写文件流
try {
download(is, randomAccessFile);
} catch (IOException e) {
e.printStackTrace();
mDownloadInfo.setNetworkSpeed(0);
mDownloadInfo.setState(DownloadManager.ERROR);
postMessage("文件读写异常", e);
return mDownloadInfo;
}
//循环结束走到这里,a.下载完成 b.暂停 c.判断是否下载出错
if (isCancelled()) {
mDownloadInfo.setNetworkSpeed(0);
if (//暂停
isPause)
//暂停
mDownloadInfo.setState(DownloadManager.PAUSE);
else
//停止
mDownloadInfo.setState(DownloadManager.NONE);
postMessage(null, null);
} else if (file.length() == mDownloadInfo.getTotalLength() && mDownloadInfo.getState() == DownloadManager.DOWNLOADING) {
mDownloadInfo.setNetworkSpeed(0);
//下载完成
mDownloadInfo.setState(DownloadManager.FINISH);
postMessage(null, null);
} else if (file.length() != mDownloadInfo.getDownloadLength()) {
mDownloadInfo.setNetworkSpeed(0);
//由于不明原因,文件保存有误
mDownloadInfo.setState(DownloadManager.ERROR);
postMessage("未知原因", null);
}
return mDownloadInfo;
}
use of okhttp3.Headers in project chuck by jgilfelt.
the class ChuckInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
HttpTransaction transaction = new HttpTransaction();
transaction.setRequestDate(new Date());
transaction.setMethod(request.method());
transaction.setUrl(request.url().toString());
transaction.setRequestHeaders(request.headers());
if (hasRequestBody) {
if (requestBody.contentType() != null) {
transaction.setRequestContentType(requestBody.contentType().toString());
}
if (requestBody.contentLength() != -1) {
transaction.setRequestContentLength(requestBody.contentLength());
}
}
transaction.setRequestBodyIsPlainText(!bodyHasUnsupportedEncoding(request.headers()));
if (hasRequestBody && transaction.requestBodyIsPlainText()) {
BufferedSource source = getNativeSource(new Buffer(), bodyGzipped(request.headers()));
Buffer buffer = source.buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (isPlaintext(buffer)) {
transaction.setRequestBody(readFromBuffer(buffer, charset));
} else {
transaction.setResponseBodyIsPlainText(false);
}
}
Uri transactionUri = create(transaction);
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
transaction.setError(e.toString());
update(transaction, transactionUri);
throw e;
}
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
// includes headers added later in the chain
transaction.setRequestHeaders(response.request().headers());
transaction.setResponseDate(new Date());
transaction.setTookMs(tookMs);
transaction.setProtocol(response.protocol().toString());
transaction.setResponseCode(response.code());
transaction.setResponseMessage(response.message());
transaction.setResponseContentLength(responseBody.contentLength());
if (responseBody.contentType() != null) {
transaction.setResponseContentType(responseBody.contentType().toString());
}
transaction.setResponseHeaders(response.headers());
transaction.setResponseBodyIsPlainText(!bodyHasUnsupportedEncoding(response.headers()));
if (HttpHeaders.hasBody(response) && transaction.responseBodyIsPlainText()) {
BufferedSource source = getNativeSource(response);
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
update(transaction, transactionUri);
return response;
}
}
if (isPlaintext(buffer)) {
transaction.setResponseBody(readFromBuffer(buffer.clone(), charset));
} else {
transaction.setResponseBodyIsPlainText(false);
}
transaction.setResponseContentLength(buffer.size());
}
update(transaction, transactionUri);
return response;
}
use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.
the class FormUploadActivity method formUpload.
@OnClick(R.id.formUpload)
public void formUpload(View view) {
ArrayList<File> files = new ArrayList<>();
if (imageItems != null && imageItems.size() > 0) {
for (int i = 0; i < imageItems.size(); i++) {
files.add(new File(imageItems.get(i).path));
}
}
//拼接参数
//
OkGo.post(Urls.URL_FORM_UPLOAD).tag(//
this).headers("header1", //
"headerValue1").headers("header2", //
"headerValue2").params("param1", //
"paramValue1").params("param2", //
"paramValue2").addFileParams("file", // 这种方式为同一个key,上传多个文件
files).execute(new JsonCallback<LzyResponse<ServerModel>>() {
@Override
public void onBefore(BaseRequest request) {
super.onBefore(request);
btnFormUpload.setText("正在上传中...");
}
@Override
public void onSuccess(LzyResponse<ServerModel> responseData, Call call, Response response) {
handleResponse(responseData.data, call, response);
btnFormUpload.setText("上传完成");
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
handleError(call, response);
btnFormUpload.setText("上传出错");
}
@Override
public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
System.out.println("upProgress -- " + totalSize + " " + currentSize + " " + progress + " " + networkSpeed);
String downloadLength = Formatter.formatFileSize(getApplicationContext(), currentSize);
String totalLength = Formatter.formatFileSize(getApplicationContext(), totalSize);
tvDownloadSize.setText(downloadLength + "/" + totalLength);
String netSpeed = Formatter.formatFileSize(getApplicationContext(), networkSpeed);
tvNetSpeed.setText(netSpeed + "/S");
tvProgress.setText((Math.round(progress * 10000) * 1.0f / 100) + "%");
pbProgress.setMax(100);
pbProgress.setProgress((int) (progress * 100));
}
});
}
use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.
the class SyncActivity method sync.
@OnClick(R.id.sync)
public void sync(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//同步会阻塞主线程,必须开线程
Response response = //
OkGo.get(Urls.URL_JSONOBJECT).tag(//
this).headers("header1", //
"headerValue1").params("param1", //
"paramValue1").execute();
Message message = Message.obtain();
message.obj = response;
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.
the class CacheCall method execute.
@Override
public void execute(AbsCallback<T> callback) {
synchronized (this) {
if (executed)
throw new IllegalStateException("Already executed.");
executed = true;
}
mCallback = callback;
if (mCallback == null)
mCallback = new AbsCallbackWrapper<>();
//请求执行前UI线程调用
mCallback.onBefore(baseRequest);
//请求之前获取缓存信息,添加缓存头和其他的公共头
if (baseRequest.getCacheKey() == null)
baseRequest.setCacheKey(HttpUtils.createUrlFromParams(baseRequest.getBaseUrl(), baseRequest.getParams().urlParamsMap));
if (baseRequest.getCacheMode() == null)
baseRequest.setCacheMode(CacheMode.NO_CACHE);
//无缓存模式,不需要进入缓存逻辑
final CacheMode cacheMode = baseRequest.getCacheMode();
if (cacheMode != CacheMode.NO_CACHE) {
//noinspection unchecked
cacheEntity = (CacheEntity<T>) CacheManager.INSTANCE.get(baseRequest.getCacheKey());
//检查缓存的有效时间,判断缓存是否已经过期
if (cacheEntity != null && cacheEntity.checkExpire(cacheMode, baseRequest.getCacheTime(), System.currentTimeMillis())) {
cacheEntity.setExpire(true);
}
HeaderParser.addCacheHeaders(baseRequest, cacheEntity, cacheMode);
}
//构建请求
RequestBody requestBody = baseRequest.generateRequestBody();
final Request request = baseRequest.generateRequest(baseRequest.wrapRequestBody(requestBody));
rawCall = baseRequest.generateCall(request);
if (cacheMode == CacheMode.IF_NONE_CACHE_REQUEST) {
//如果没有缓存,或者缓存过期,就请求网络,否者直接使用缓存
if (cacheEntity != null && !cacheEntity.isExpire()) {
T data = cacheEntity.getData();
HttpHeaders headers = cacheEntity.getResponseHeaders();
if (data == null || headers == null) {
//由于没有序列化等原因,可能导致数据为空
sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
} else {
sendSuccessResultCallback(true, data, rawCall, null);
//获取缓存成功,不请求网络
return;
}
} else {
sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
}
} else if (cacheMode == CacheMode.FIRST_CACHE_THEN_REQUEST) {
//先使用缓存,不管是否存在,仍然请求网络
if (cacheEntity != null && !cacheEntity.isExpire()) {
T data = cacheEntity.getData();
HttpHeaders headers = cacheEntity.getResponseHeaders();
if (data == null || headers == null) {
//由于没有序列化等原因,可能导致数据为空
sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
} else {
sendSuccessResultCallback(true, data, rawCall, null);
}
} else {
sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
}
}
if (canceled) {
rawCall.cancel();
}
currentRetryCount = 0;
rawCall.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
if (e instanceof SocketTimeoutException && currentRetryCount < baseRequest.getRetryCount()) {
//超时重试处理
currentRetryCount++;
okhttp3.Call newCall = baseRequest.generateCall(call.request());
newCall.enqueue(this);
} else {
mCallback.parseError(call, e);
//请求失败,一般为url地址错误,网络错误等,并且过滤用户主动取消的网络请求
if (!call.isCanceled()) {
sendFailResultCallback(false, call, null, e);
}
}
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
int responseCode = response.code();
//304缓存数据
if (responseCode == 304 && cacheMode == CacheMode.DEFAULT) {
if (cacheEntity == null) {
sendFailResultCallback(true, call, response, OkGoException.INSTANCE("服务器响应码304,但是客户端没有缓存!"));
} else {
T data = cacheEntity.getData();
HttpHeaders headers = cacheEntity.getResponseHeaders();
if (data == null || headers == null) {
//由于没有序列化等原因,可能导致数据为空
sendFailResultCallback(true, call, response, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
} else {
sendSuccessResultCallback(true, data, call, response);
}
}
return;
}
//响应失败,一般为服务器内部错误,或者找不到页面等
if (responseCode == 404 || responseCode >= 500) {
sendFailResultCallback(false, call, response, OkGoException.INSTANCE("服务器数据异常!"));
return;
}
try {
Response<T> parseResponse = parseResponse(response);
T data = parseResponse.body();
//网络请求成功,保存缓存数据
handleCache(response.headers(), data);
//网络请求成功回调
sendSuccessResultCallback(false, data, call, response);
} catch (Exception e) {
//一般为服务器响应成功,但是数据解析错误
sendFailResultCallback(false, call, response, e);
}
}
});
}
Aggregations