Example usage for com.squareup.okhttp Response newBuilder

List of usage examples for com.squareup.okhttp Response newBuilder

Introduction

In this page you can find the example usage for com.squareup.okhttp Response newBuilder.

Prototype

public Builder newBuilder() 

Source Link

Usage

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call getSessionParticipantsCall(String sessionId, Boolean deletedParticipants,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // create path and map variables
    String localVarPath = "/sessions/{session_id}/participants".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "session_id" + "\\}", apiClient.escapeString(sessionId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    if (deletedParticipants != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "deleted_participants", deletedParticipants));

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };/*from w ww .ja v a2s.  co  m*/
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call updateSessionCall(String sessionId, SessionUpdateRequest body,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = body;

    // create path and map variables
    String localVarPath = "/sessions/{session_id}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "session_id" + "\\}", apiClient.escapeString(sessionId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json" };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override/*from   www  . j  av a  2  s.c o m*/
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call updateSessionParticipantCall(String participantId,
        ParticipantUpdateRequest body, final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = body;

    // create path and map variables
    String localVarPath = "/participants/{participant_id}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "participant_id" + "\\}", apiClient.escapeString(participantId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json" };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override//from  w  w w. j a  v a 2 s.c  om
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.dreamdigitizers.androidsoundcloudapi.core.Api.java

private Api(final String pClientId, final String pOauthToken) {
    OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.interceptors().add(new Interceptor() {
        @Override/*from  w  w w.  j a v a2s .  c o m*/
        public Response intercept(Chain pChain) throws IOException {
            Request request = pChain.request();
            HttpUrl.Builder builder = request.httpUrl().newBuilder();
            builder.addQueryParameter("client_id", pClientId);
            if (!TextUtils.isEmpty(pOauthToken)) {
                builder.addQueryParameter("oauth_token", pOauthToken);
            }
            HttpUrl httpUrl = builder.build();
            Log.d(Api.TAG, httpUrl.url().toString());
            request = request.newBuilder().url(httpUrl).build();
            Response response = pChain.proceed(request);
            String bodyString = response.body().string();
            response = response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString)).build();
            Log.d(Api.TAG, bodyString);
            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(IApi.API_URL__BASE).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    this.mApi = retrofit.create(IApi.class);
}

From source file:com.example.data.net.interceptor.CacheResponseInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    return originalResponse.newBuilder().header("Cache-Control", CACHE_CONTROL_PARAMS).build();
}

From source file:com.facebook.stetho.okhttp.StethoInterceptor.java

License:Open Source License

@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);//from  ww w .  j  a va 2 s .  c o m
        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;
}

From source file:com.gdkm.sfk.utils.coreProgress.ProgressHelper.java

License:Apache License

/**
 * OkHttpClient/*  www  .  ja  v  a2  s  . c o m*/
 * @param client OkHttpClient
 * @param progressListener ?
 * @return ?OkHttpClientclone
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client,
        final ProgressResponseListener progressListener) {
    //
    OkHttpClient clone = client.clone();
    //
    clone.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //
            Response originalResponse = chain.proceed(chain.request());
            //?
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
        }
    });
    return clone;
}

From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.java

License:Apache License

private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse, com.squareup.okhttp.Request request)
        throws IOException {
    ResponseBody rawBody = rawResponse.body();
    // rawResponse.r
    // Remove the body's source (the only stateful object) so we can pass
    // the response along.
    rawResponse = rawResponse.newBuilder()
            .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();

    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {//from  w w  w.j  a v a2s .co  m
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            closeQuietly(rawBody);
        }
    }

    if (code == 204 || code == 205) {
        return Response.success(null, rawResponse);
    }

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {

        T body;
        if (responseConverter instanceof GsonConverter) {
            GsonConverter<T> converter = (GsonConverter<T>) responseConverter;
            body = converter.fromBody(catchingBody, request);
        } else {
            body = responseConverter.fromBody(catchingBody);
        }
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that
        // rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    }
}

From source file:com.magnet.max.android.rest.qos.internal.CachedResponse.java

License:Apache License

public Response toResponse(Request request) {
    Headers responseHeaders = Headers.of(headers);
    String contentType = responseHeaders.get("Content-Type");
    Response cachedResponse = new Response.Builder().code(code).protocol(getProtocolEnum()).message(message)
            .headers(responseHeaders).request(request).build();
    return cachedResponse.newBuilder().body(ResponseBody.create(MediaType.parse(contentType), body))
            .cacheResponse(cachedResponse).build();
}

From source file:com.magnet.max.android.rest.qos.internal.CacheManager.java

License:Apache License

public Response cacheResponse(Request request, Response response, CacheOptions options) {
    String requestHash = CacheUtils.getRequestHash(request);
    ResponseCacheEntity operation = findLatestCache(requestHash, request, options);
    long currentTimestamp = System.currentTimeMillis();
    if (null == operation) {
        operation = new ResponseCacheEntity();
        operation.createdAt = currentTimestamp;
        operation.url = request.urlString();
        operation.httpMethod = request.method();
        operation.requestHash = requestHash;
        operation.response = new CachedResponse(response);
        operation.responseCode = response.code();
        operation.isOfflineCache = options.isAlwaysUseCacheIfOffline();

        Log.d(TAG, "Adding cache for request " + request);
    } else {//from   w  w  w  . ja  va  2 s.co m
        //Update body
        operation.response = new CachedResponse(response);
        Log.d(TAG, "Updating cache for request " + request);
    }
    operation.updatedAt = currentTimestamp;
    long newExpiredTime = 0;
    if (options.getMaxCacheAge() > 0) {
        newExpiredTime = currentTimestamp + options.getMaxCacheAge() * 1000;
    }
    if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) {
        operation.expiredAt = newExpiredTime;
    }
    operation.save();

    if (null != response.body()) {
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), operation.response.body)).build();
    } else {
        return response;
    }
}