Search in sources :

Example 56 with RequestBody

use of okhttp3.RequestBody 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 57 with RequestBody

use of okhttp3.RequestBody in project MVCHelper by LuckyJayce.

the class PostFileMethod method buildRequset.

@Override
protected Request.Builder buildRequset(String url, Map<String, Object> params) {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    if (params != null) {
        for (Entry<String, ?> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    if (httpbodys != null) {
        for (Entry<String, Data2<String, RequestBody>> entry : httpbodys.entrySet()) {
            String key = entry.getKey();
            Data2<String, RequestBody> body = entry.getValue();
            builder.addFormDataPart(key, body.getValue1(), body.getValue2());
        }
    }
    RequestBody formBody = builder.build();
    if (listener != null) {
        formBody = new CountingRequestBody(formBody, listener);
    }
    return new Request.Builder().url(url).post(formBody);
}
Also used : Data2(com.shizhefei.mvc.data.Data2) MultipartBody(okhttp3.MultipartBody) RequestBody(okhttp3.RequestBody)

Example 58 with RequestBody

use of okhttp3.RequestBody in project MVCHelper by LuckyJayce.

the class PostMethod method buildRequset.

@Override
protected Request.Builder buildRequset(String url, Map<String, Object> params) {
    FormBody.Builder builder = new FormBody.Builder();
    if (params != null) {
        for (Entry<String, ?> entry : params.entrySet()) {
            builder.add(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    RequestBody formBody = builder.build();
    return new Request.Builder().url(url).post(formBody);
}
Also used : FormBody(okhttp3.FormBody) RequestBody(okhttp3.RequestBody)

Example 59 with RequestBody

use of okhttp3.RequestBody in project MVCHelper by LuckyJayce.

the class PutMethod method buildRequset.

@Override
protected Request.Builder buildRequset(String url, Map<String, Object> params) {
    FormBody.Builder builder = new FormBody.Builder();
    if (params != null) {
        for (Entry<String, ?> entry : params.entrySet()) {
            builder.add(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    RequestBody formBody = builder.build();
    return new Request.Builder().url(url).put(formBody);
}
Also used : FormBody(okhttp3.FormBody) RequestBody(okhttp3.RequestBody)

Example 60 with RequestBody

use of okhttp3.RequestBody in project Reader by TheKeeperOfPie.

the class ActivityLogin method fetchTokens.

private void fetchTokens(String code) {
    RequestBody requestBody = new FormBody.Builder().add(Reddit.QUERY_GRANT_TYPE, Reddit.CODE_GRANT).add(Reddit.QUERY_CODE, code).add(Reddit.QUERY_REDIRECT_URI, Reddit.REDIRECT_URI).build();
    Request request = Reddit.withRequestBasicAuth().url(Reddit.ACCESS_URL).post(requestBody).build();
    reddit.load(request).subscribe(new FinalizingSubscriber<String>() {

        @Override
        public void next(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                String tokenAccess = jsonObject.getString(Reddit.QUERY_ACCESS_TOKEN);
                String tokenRefresh = jsonObject.getString(Reddit.QUERY_REFRESH_TOKEN);
                long timeExpire = System.currentTimeMillis() + jsonObject.getLong(Reddit.QUERY_EXPIRES_IN) * Reddit.SEC_TO_MS;
                Log.d(TAG, "timeExpire in: " + jsonObject.getLong(Reddit.QUERY_EXPIRES_IN));
                loadAccountInfo(tokenAccess, tokenRefresh, timeExpire);
            } catch (JSONException e) {
                onError(e);
            }
        }

        @Override
        public void error(Throwable e) {
            Toast.makeText(ActivityLogin.this, R.string.error_logging_in, Toast.LENGTH_LONG).show();
        }
    });
}
Also used : JSONObject(org.json.JSONObject) WebResourceRequest(android.webkit.WebResourceRequest) Request(okhttp3.Request) JSONException(org.json.JSONException) RequestBody(okhttp3.RequestBody)

Aggregations

RequestBody (okhttp3.RequestBody)178 Request (okhttp3.Request)141 IOException (java.io.IOException)75 Response (okhttp3.Response)74 Test (org.junit.Test)53 ResponseBody (okhttp3.ResponseBody)32 Call (okhttp3.Call)31 MultipartBody (okhttp3.MultipartBody)28 MediaType (okhttp3.MediaType)27 FormBody (okhttp3.FormBody)25 Callback (okhttp3.Callback)23 Buffer (okio.Buffer)23 MockResponse (okhttp3.mockwebserver.MockResponse)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestClients.clientRequest (keywhiz.TestClients.clientRequest)15 BufferedSink (okio.BufferedSink)15 Headers (okhttp3.Headers)12 HttpUrl (okhttp3.HttpUrl)11 JSONObject (org.json.JSONObject)11 Body (retrofit2.http.Body)11