Search in sources :

Example 1 with BaseRequest

use of com.lzy.okgo.request.BaseRequest 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));
        }
    });
}
Also used : Call(okhttp3.Call) LzyResponse(com.lzy.demo.model.LzyResponse) ArrayList(java.util.ArrayList) Response(okhttp3.Response) LzyResponse(com.lzy.demo.model.LzyResponse) ServerModel(com.lzy.demo.model.ServerModel) BaseRequest(com.lzy.okgo.request.BaseRequest) File(java.io.File) OnClick(butterknife.OnClick)

Example 2 with BaseRequest

use of com.lzy.okgo.request.BaseRequest 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);
            }
        }
    });
}
Also used : HttpHeaders(com.lzy.okgo.model.HttpHeaders) Request(okhttp3.Request) BaseRequest(com.lzy.okgo.request.BaseRequest) CacheMode(com.lzy.okgo.cache.CacheMode) IOException(java.io.IOException) OkGoException(com.lzy.okgo.exception.OkGoException) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) Response(com.lzy.okgo.model.Response) AbsCallbackWrapper(com.lzy.okgo.callback.AbsCallbackWrapper) SocketTimeoutException(java.net.SocketTimeoutException) RequestBody(okhttp3.RequestBody)

Example 3 with BaseRequest

use of com.lzy.okgo.request.BaseRequest in project okhttp-OkGo by jeasonlzy.

the class DownloadInfo method buildContentValues.

public static ContentValues buildContentValues(DownloadInfo downloadInfo) {
    ContentValues values = new ContentValues();
    values.put(TASK_KEY, downloadInfo.getTaskKey());
    values.put(URL, downloadInfo.getUrl());
    values.put(TARGET_FOLDER, downloadInfo.getTargetFolder());
    values.put(TARGET_PATH, downloadInfo.getTargetPath());
    values.put(FILE_NAME, downloadInfo.getFileName());
    values.put(PROGRESS, downloadInfo.getProgress());
    values.put(TOTAL_LENGTH, downloadInfo.getTotalLength());
    values.put(DOWNLOAD_LENGTH, downloadInfo.getDownloadLength());
    values.put(NETWORK_SPEED, downloadInfo.getNetworkSpeed());
    values.put(STATE, downloadInfo.getState());
    BaseRequest request = downloadInfo.getRequest();
    DownloadRequest downloadRequest = downloadInfo.getDownloadRequest();
    downloadRequest.cacheKey = request.getCacheKey();
    downloadRequest.cacheTime = request.getCacheTime();
    downloadRequest.cacheMode = request.getCacheMode();
    downloadRequest.url = request.getBaseUrl();
    downloadRequest.params = request.getParams();
    downloadRequest.headers = request.getHeaders();
    downloadRequest.method = DownloadRequest.getMethod(request);
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(downloadRequest);
        oos.flush();
        byte[] requestData = baos.toByteArray();
        values.put(DownloadInfo.DOWNLOAD_REQUEST, requestData);
    } catch (IOException e) {
        OkLogger.e(e);
    } finally {
        try {
            if (oos != null)
                oos.close();
            if (baos != null)
                baos.close();
        } catch (IOException e) {
            OkLogger.e(e);
        }
    }
    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(downloadInfo.getData());
        oos.flush();
        byte[] data = baos.toByteArray();
        values.put(DownloadInfo.DATA, data);
    } catch (IOException e) {
        OkLogger.e(e);
    } finally {
        try {
            if (oos != null)
                oos.close();
            if (baos != null)
                baos.close();
        } catch (IOException e) {
            OkLogger.e(e);
        }
    }
    return values;
}
Also used : ContentValues(android.content.ContentValues) BaseRequest(com.lzy.okgo.request.BaseRequest) DownloadRequest(com.lzy.okserver.download.db.DownloadRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ObjectOutputStream(java.io.ObjectOutputStream)

Example 4 with BaseRequest

use of com.lzy.okgo.request.BaseRequest in project okhttp-OkGo by jeasonlzy.

the class DownloadInfo method parseCursorToBean.

public static DownloadInfo parseCursorToBean(Cursor cursor) {
    DownloadInfo info = new DownloadInfo();
    info.setId(cursor.getInt(cursor.getColumnIndex(DownloadInfo.ID)));
    info.setTaskKey(cursor.getString(cursor.getColumnIndex(DownloadInfo.TASK_KEY)));
    info.setUrl(cursor.getString(cursor.getColumnIndex(DownloadInfo.URL)));
    info.setTargetFolder(cursor.getString(cursor.getColumnIndex(DownloadInfo.TARGET_FOLDER)));
    info.setTargetPath(cursor.getString(cursor.getColumnIndex(DownloadInfo.TARGET_PATH)));
    info.setFileName(cursor.getString(cursor.getColumnIndex(DownloadInfo.FILE_NAME)));
    info.setProgress(cursor.getFloat(cursor.getColumnIndex(DownloadInfo.PROGRESS)));
    info.setTotalLength(cursor.getLong(cursor.getColumnIndex(DownloadInfo.TOTAL_LENGTH)));
    info.setDownloadLength(cursor.getLong(cursor.getColumnIndex(DownloadInfo.DOWNLOAD_LENGTH)));
    info.setNetworkSpeed(cursor.getLong(cursor.getColumnIndex(DownloadInfo.NETWORK_SPEED)));
    info.setState(cursor.getInt(cursor.getColumnIndex(DownloadInfo.STATE)));
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    byte[] requestData = cursor.getBlob(cursor.getColumnIndex(DownloadInfo.DOWNLOAD_REQUEST));
    try {
        if (requestData != null) {
            bais = new ByteArrayInputStream(requestData);
            ois = new ObjectInputStream(bais);
            DownloadRequest downloadRequest = (DownloadRequest) ois.readObject();
            info.setDownloadRequest(downloadRequest);
            BaseRequest request = DownloadRequest.createRequest(downloadRequest.url, downloadRequest.method);
            if (request != null) {
                request.cacheMode(downloadRequest.cacheMode);
                request.cacheTime(downloadRequest.cacheTime);
                request.cacheKey(downloadRequest.cacheKey);
                request.params(downloadRequest.params);
                request.headers(downloadRequest.headers);
                info.setRequest(request);
            }
        }
    } catch (Exception e) {
        OkLogger.e(e);
    } finally {
        try {
            if (ois != null)
                ois.close();
            if (bais != null)
                bais.close();
        } catch (IOException e) {
            OkLogger.e(e);
        }
    }
    byte[] data = cursor.getBlob(cursor.getColumnIndex(DownloadInfo.DATA));
    try {
        if (data != null) {
            bais = new ByteArrayInputStream(data);
            ois = new ObjectInputStream(bais);
            Serializable serializableData = (Serializable) ois.readObject();
            info.setData(serializableData);
        }
    } catch (Exception e) {
        OkLogger.e(e);
    } finally {
        try {
            if (ois != null)
                ois.close();
            if (bais != null)
                bais.close();
        } catch (IOException e) {
            OkLogger.e(e);
        }
    }
    return info;
}
Also used : Serializable(java.io.Serializable) ByteArrayInputStream(java.io.ByteArrayInputStream) BaseRequest(com.lzy.okgo.request.BaseRequest) DownloadRequest(com.lzy.okserver.download.db.DownloadRequest) IOException(java.io.IOException) IOException(java.io.IOException) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

BaseRequest (com.lzy.okgo.request.BaseRequest)4 IOException (java.io.IOException)3 DownloadRequest (com.lzy.okserver.download.db.DownloadRequest)2 ContentValues (android.content.ContentValues)1 OnClick (butterknife.OnClick)1 LzyResponse (com.lzy.demo.model.LzyResponse)1 ServerModel (com.lzy.demo.model.ServerModel)1 CacheMode (com.lzy.okgo.cache.CacheMode)1 AbsCallbackWrapper (com.lzy.okgo.callback.AbsCallbackWrapper)1 OkGoException (com.lzy.okgo.exception.OkGoException)1 HttpHeaders (com.lzy.okgo.model.HttpHeaders)1 Response (com.lzy.okgo.model.Response)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 ObjectInputStream (java.io.ObjectInputStream)1 ObjectOutputStream (java.io.ObjectOutputStream)1 Serializable (java.io.Serializable)1 SocketTimeoutException (java.net.SocketTimeoutException)1 ArrayList (java.util.ArrayList)1