Search in sources :

Example 16 with okhttp3

use of okhttp3 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 17 with okhttp3

use of okhttp3 in project Rocket.Chat.Android by RocketChat.

the class DefaultServerPolicyApi method getOkHttpCallback.

private okhttp3.Callback getOkHttpCallback(@NonNull FlowableEmitter<Response<JSONObject>> emitter, @NonNull String protocol) {
    return new okhttp3.Callback() {

        @Override
        public void onFailure(Call call, IOException ioException) {
            if (emitter.isCancelled()) {
                return;
            }
            emitter.onError(ioException);
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            if (emitter.isCancelled()) {
                return;
            }
            if (!response.isSuccessful()) {
                emitter.onNext(new Response<>(false, protocol, null));
                emitter.onComplete();
                return;
            }
            final ResponseBody body = response.body();
            if (body == null || body.contentLength() == 0) {
                emitter.onNext(new Response<>(false, protocol, null));
                emitter.onComplete();
                return;
            }
            try {
                emitter.onNext(new Response<>(true, protocol, new JSONObject(body.string())));
            } catch (Exception e) {
                emitter.onNext(new Response<>(false, protocol, null));
            }
            emitter.onComplete();
        }
    };
}
Also used : Call(okhttp3.Call) JSONObject(org.json.JSONObject) IOException(java.io.IOException) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 18 with okhttp3

use of okhttp3 in project Gradle-demo by Arisono.

the class OkhttpUtils method initClient.

public static void initClient(HttpClient mbuilder) {
    //本类保证初始化一次,减少系统开销
    okhttp3.OkHttpClient.Builder okBuilder = client.newBuilder().connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS).readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS).writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS).sslSocketFactory(OkhttpUtils.createSSLSocketFactory(), //信任所有证书
    new TrustAllCerts()).hostnameVerifier(new TrustAllHostnameVerifier());
    LogInterceptor logInterceptor = new LogInterceptor();
    logInterceptor.setBuilder(mbuilder);
    okBuilder.addInterceptor(logInterceptor);
    client = okBuilder.build();
}
Also used : TrustAllHostnameVerifier(com.gradle.android.retrofit.OkhttpUtils.TrustAllHostnameVerifier) OkHttpClient(okhttp3.OkHttpClient) LogInterceptor(com.gradle.android.Interceptor.LogInterceptor) TrustAllCerts(com.gradle.android.retrofit.OkhttpUtils.TrustAllCerts)

Example 19 with okhttp3

use of okhttp3 in project PokeGOAPI-Java by Grover-c13.

the class RequestHandler method sendInternal.

/**
	 * Sends an already built request envelope
	 *
	 * @param serverResponse the response to append to
	 * @param requests list of ServerRequests to be sent
	 * @param platformRequests list of ServerPlatformRequests to be sent
	 * @param builder the request envelope builder
	 * @throws RequestFailedException if this message fails to send
	 */
private ServerResponse sendInternal(ServerResponse serverResponse, ServerRequest[] requests, ServerPlatformRequest[] platformRequests, RequestEnvelope.Builder builder) throws RequestFailedException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    RequestEnvelope request = builder.build();
    try {
        request.writeTo(stream);
    } catch (IOException e) {
        Log.wtf(TAG, "Failed to write request to bytearray ouput stream. This should never happen", e);
    }
    RequestBody body = RequestBody.create(null, stream.toByteArray());
    okhttp3.Request httpRequest = new okhttp3.Request.Builder().url(apiEndpoint).post(body).build();
    try (Response response = client.newCall(httpRequest).execute()) {
        if (response.code() != 200) {
            throw new RequestFailedException("Got a unexpected http code : " + response.code());
        }
        ResponseEnvelope responseEnvelop;
        try (InputStream content = response.body().byteStream()) {
            responseEnvelop = ResponseEnvelope.parseFrom(content);
        } catch (IOException e) {
            // retrieved garbage from the server
            throw new RequestFailedException("Received malformed response : " + e);
        }
        if (responseEnvelop.getApiUrl() != null && responseEnvelop.getApiUrl().length() > 0) {
            apiEndpoint = "https://" + responseEnvelop.getApiUrl() + "/rpc";
        }
        if (responseEnvelop.hasAuthTicket()) {
            this.authTicket = responseEnvelop.getAuthTicket();
        }
        boolean empty = false;
        StatusCode statusCode = responseEnvelop.getStatusCode();
        if (statusCode != StatusCode.REDIRECT && statusCode != StatusCode.INVALID_AUTH_TOKEN) {
            for (int i = 0; i < responseEnvelop.getReturnsCount(); i++) {
                ByteString returned = responseEnvelop.getReturns(i);
                ServerRequest serverRequest = requests[i];
                if (returned != null) {
                    serverResponse.addResponse(serverRequest.getType(), returned);
                    if (serverRequest.getType() == RequestType.GET_PLAYER) {
                        if (GetPlayerResponse.parseFrom(returned).getBanned()) {
                            throw new BannedException("Cannot send request, your account has been banned!");
                        }
                    }
                } else {
                    empty = true;
                }
            }
        }
        for (int i = 0; i < responseEnvelop.getPlatformReturnsCount(); i++) {
            PlatformResponse platformResponse = responseEnvelop.getPlatformReturns(i);
            ByteString returned = platformResponse.getResponse();
            if (returned != null) {
                serverResponse.addResponse(platformResponse.getType(), returned);
            }
        }
        if (statusCode != StatusCode.OK && statusCode != StatusCode.OK_RPC_URL_IN_RESPONSE) {
            if (statusCode == StatusCode.INVALID_AUTH_TOKEN) {
                try {
                    authTicket = null;
                    api.getAuthInfo(true);
                    return sendInternal(serverResponse, requests, platformRequests);
                } catch (LoginFailedException | InvalidCredentialsException e) {
                    throw new RequestFailedException("Failed to refresh auth token!", e);
                } catch (RequestFailedException e) {
                    throw new RequestFailedException("Failed to send request with refreshed auth token!", e);
                }
            } else if (statusCode == StatusCode.REDIRECT) {
                // API_ENDPOINT was not correctly set, should be at this point, though, so redo the request
                return sendInternal(serverResponse, requests, platformRequests, builder);
            } else if (statusCode == StatusCode.BAD_REQUEST) {
                if (api.getPlayerProfile().isBanned()) {
                    throw new BannedException("Cannot send request, your account has been banned!");
                } else {
                    throw new BadRequestException("A bad request was sent!");
                }
            } else {
                throw new RequestFailedException("Failed to send request: " + statusCode);
            }
        }
        if (empty) {
            throw new RequestFailedException("Received empty response from server!");
        }
    } catch (IOException e) {
        throw new RequestFailedException(e);
    } catch (RequestFailedException e) {
        throw e;
    }
    return serverResponse;
}
Also used : InputStream(java.io.InputStream) ByteString(com.google.protobuf.ByteString) PlatformRequest(POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.PlatformRequest) Request(POGOProtos.Networking.Requests.RequestOuterClass.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) StatusCode(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode) PlatformResponse(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse) Response(okhttp3.Response) GetPlayerResponse(POGOProtos.Networking.Responses.GetPlayerResponseOuterClass.GetPlayerResponse) ResponseEnvelope(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) BannedException(com.pokegoapi.exceptions.request.BannedException) RequestEnvelope(POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope) BadRequestException(com.pokegoapi.exceptions.request.BadRequestException) PlatformResponse(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse) RequestBody(okhttp3.RequestBody)

Example 20 with okhttp3

use of okhttp3 in project spring-framework by spring-projects.

the class OkHttp3ClientHttpRequestFactory method buildRequest.

static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method) throws MalformedURLException {
    okhttp3.MediaType contentType = getContentType(headers);
    RequestBody body = (content.length > 0 || okhttp3.internal.http.HttpMethod.requiresRequestBody(method.name()) ? RequestBody.create(contentType, content) : null);
    Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body);
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            builder.addHeader(headerName, headerValue);
        }
    }
    return builder.build();
}
Also used : Request(okhttp3.Request) List(java.util.List) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)25 IOException (java.io.IOException)20 Test (org.junit.Test)16 ResponseBody (okhttp3.ResponseBody)12 OkHttpClient (okhttp3.OkHttpClient)10 Response (okhttp3.Response)9 RequestBody (okhttp3.RequestBody)8 MockResponse (okhttp3.mockwebserver.MockResponse)8 Call (okhttp3.Call)5 Interceptor (okhttp3.Interceptor)5 Map (java.util.Map)4 Retrofit (retrofit2.Retrofit)4 Header (retrofit2.http.Header)4 List (java.util.List)3 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)3 Response (retrofit2.Response)3 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)3 HashMap (java.util.HashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Level (java.util.logging.Level)2