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.oracle.bdcs.bdm.client.api.Users.java

License:Apache License

private com.squareup.okhttp.Call updateUserCall(String tenantName, String userUuid, User body,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = body;

    // verify the required parameter 'tenantName' is set
    if (tenantName == null) {
        throw new ApiException("Missing the required parameter 'tenantName' when calling updateUser(Async)");
    }/*from  w  w  w .  j  a  v a2 s.c o m*/

    // verify the required parameter 'userUuid' is set
    if (userUuid == null) {
        throw new ApiException("Missing the required parameter 'userUuid' when calling updateUser(Async)");
    }

    // verify the required parameter 'body' is set
    if (body == null) {
        throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)");
    }

    // create path and map variables
    String localVarPath = "/v1.0/tenants/{tenantName}/users/{userUuid}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "tenantName" + "\\}", apiClient.escapeString(tenantName.toString()))
            .replaceAll("\\{" + "userUuid" + "\\}", apiClient.escapeString(userUuid.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 = {

    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };
    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[] {};
    return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java

License:Apache License

private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();

    // 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 .  ja v a 2 s.c  o  m*/
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            Utils.closeQuietly(rawBody);
        }
    }

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

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
        T body = responseConverter.convert(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.parse.ParseOkHttpClient.java

License:Open Source License

/**
 * For OKHttpClient, since it does not expose any interface for us to check the raw response
 * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
 * we use OKHttp inner interceptor list.
 * @param parseNetworkInterceptor/* ww w  .  ja  v  a  2 s.  c  o  m*/
 */
@Override
/* package */ void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
    okHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(final Chain okHttpChain) throws IOException {
            Request okHttpRequest = okHttpChain.request();
            // Transfer OkHttpRequest to ParseHttpRequest
            final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
            // Capture OkHttpResponse
            final Capture<Response> okHttpResponseCapture = new Capture<>();
            final ParseHttpResponse parseResponse = parseNetworkInterceptor
                    .intercept(new ParseNetworkInterceptor.Chain() {
                        @Override
                        public ParseHttpRequest getRequest() {
                            return parseRequest;
                        }

                        @Override
                        public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
                            // Use OKHttpClient to send request
                            Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
                            Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
                            okHttpResponseCapture.set(okHttpResponse);
                            return getResponse(okHttpResponse);
                        }
                    });
            final Response okHttpResponse = okHttpResponseCapture.get();
            // Ideally we should build newOkHttpResponse only based on parseResponse, however
            // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
            // we rely on the okHttpResponse to generate the builder and change the necessary info
            // inside
            Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
            // Set status
            newOkHttpResponseBuilder.code(parseResponse.getStatusCode())
                    .message(parseResponse.getReasonPhrase());
            // Set headers
            if (parseResponse.getAllHeaders() != null) {
                for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
                    newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
                }
            }
            // Set body
            newOkHttpResponseBuilder.body(new ResponseBody() {
                @Override
                public MediaType contentType() {
                    if (parseResponse.getContentType() == null) {
                        return null;
                    }
                    return MediaType.parse(parseResponse.getContentType());
                }

                @Override
                public long contentLength() throws IOException {
                    return parseResponse.getTotalSize();
                }

                @Override
                public BufferedSource source() throws IOException {
                    // We need to use the proxy stream from interceptor to replace the origin network
                    // stream, so when the stream is read by Parse, the network stream is proxyed in the
                    // interceptor.
                    if (parseResponse.getContent() == null) {
                        return null;
                    }
                    return Okio.buffer(Okio.source(parseResponse.getContent()));
                }
            });

            return newOkHttpResponseBuilder.build();
        }
    });
}

From source file:com.rafagarcia.countries.backend.webapi.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }//  w w  w  .  j  a  va2 s  .com

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' '
            + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody && hasRequestBody) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                contentType.charset(UTF8);
            }

            logger.log("");
            logger.log(buffer.readString(charset));
        }

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            endMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(buffer);

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (responseBody.contentLength() > 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:com.shopify.buy.data.MockResponseGenerator.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    File file = new File(context.getExternalFilesDir(null), "MobileBuy.json");

    if (file == null) {
        return chain.proceed(chain.request());
    }/*from  w w w.  ja v  a 2  s.  c  o m*/

    if (!file.exists()) {
        file.createNewFile();
    }

    String jsonKey = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement());

    Request request = chain.request();
    Response response = chain.proceed(request);
    String bodyString = response.body().string();

    JsonObject jsonValue = new JsonObject();
    jsonValue.addProperty(MockResponder.KEY_BODY, bodyString);
    jsonValue.addProperty(MockResponder.KEY_CODE, response.code());
    jsonValue.addProperty(MockResponder.KEY_MESSAGE, response.message());

    FileOutputStream fOut = new FileOutputStream(file, true);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(fOut));
    writer.println("\"" + jsonKey + "\":" + jsonValue.toString() + ",");

    if (!isPartialAddressTestAdded.getAndSet(true)) {
        writer.println(TEST_WITH_PARTIAL_ADDRESS_RESPONSE);
    }

    writer.flush();
    fOut.flush();
    writer.close();
    fOut.close();

    MediaType contentType = response.body().contentType();
    return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
}

From source file:com.sphereon.sdk.template.processor.api.AllApi.java

License:Apache License

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

    // verify the required parameter 'payload' is set
    if (payload == null) {
        throw new ApiException("Missing the required parameter 'payload' when calling createDataSet(Async)");
    }//from  ww  w.j ava 2 s .c o  m

    // create path and map variables
    String localVarPath = "/template/processor/0.1/datasets".replaceAll("\\{format\\}", "json");

    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;charset=UTF-8" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json;charset=UTF-8" };
    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[] { "oauth2schema" };
    return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.sphereon.sdk.template.processor.api.AllApi.java

License:Apache License

private com.squareup.okhttp.Call createTemplateContextCall(TemplateContextRequest templateRequest,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = templateRequest;

    // verify the required parameter 'templateRequest' is set
    if (templateRequest == null) {
        throw new ApiException(
                "Missing the required parameter 'templateRequest' when calling createTemplateContext(Async)");
    }//from   www . java  2 s .  com

    // create path and map variables
    String localVarPath = "/template/processor/0.1/templates".replaceAll("\\{format\\}", "json");

    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;charset=UTF-8" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json;charset=UTF-8" };
    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[] { "oauth2schema" };
    return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.sphereon.sdk.template.processor.api.AllApi.java

License:Apache License

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

    // verify the required parameter 'dataSetId' is set
    if (dataSetId == null) {
        throw new ApiException("Missing the required parameter 'dataSetId' when calling deleteDataSet(Async)");
    }/*from w w w  .j  a  va2s  . co  m*/

    // create path and map variables
    String localVarPath = "/template/processor/0.1/datasets/{dataSetId}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "dataSetId" + "\\}", apiClient.escapeString(dataSetId.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;charset=UTF-8" };
    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
            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[] { "oauth2schema" };
    return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.sphereon.sdk.template.processor.api.AllApi.java

License:Apache License

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

    // verify the required parameter 'jobId' is set
    if (jobId == null) {
        throw new ApiException("Missing the required parameter 'jobId' when calling deleteJob(Async)");
    }/*from  w  ww  .  j  a  va  2  s  .  c  om*/

    // create path and map variables
    String localVarPath = "/template/processor/0.1/jobs/{jobId}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "jobId" + "\\}", apiClient.escapeString(jobId.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;charset=UTF-8" };
    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
            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[] { "oauth2schema" };
    return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.sphereon.sdk.template.processor.api.AllApi.java

License:Apache License

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

    // verify the required parameter 'templateId' is set
    if (templateId == null) {
        throw new ApiException(
                "Missing the required parameter 'templateId' when calling deleteTemplateContext(Async)");
    }/*www .  j  a v  a 2 s  . c o  m*/

    // create path and map variables
    String localVarPath = "/template/processor/0.1/templates/{templateId}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "templateId" + "\\}", apiClient.escapeString(templateId.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;charset=UTF-8" };
    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
            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[] { "oauth2schema" };
    return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}