Example usage for com.squareup.okhttp Headers get

List of usage examples for com.squareup.okhttp Headers get

Introduction

In this page you can find the example usage for com.squareup.okhttp Headers get.

Prototype

public String get(String name) 

Source Link

Document

Returns the last value corresponding to the specified field, or null.

Usage

From source file:cn.com.canon.darwin.modules.service.api.interceptor.HttpLoggingInterceptor.java

License:Apache License

private boolean bodyEncoded(Headers headers) {
    String contentEncoding = headers.get("Content-Encoding");
    return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
}

From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {

    OkHttpClient requestScopedClient = clientSupplier.get();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));
    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();

    // Check for Artifactory header and init potential file for downstream use
    File destinationFile = null;/*from ww w .j  a v  a  2  s .co  m*/
    String artFileName = responseHeaders.get("X-Artifactory-Filename");
    if (artFileName != null) {

        GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(),
                endpoint.get().toURL());
        destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName,
                responseHeaders.get("ETag"));
        headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath());
    }

    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        if (destinationFile != null) {
            if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) {
                InputStream inputStream = null;
                try {
                    inputStream = response.body().byteStream();
                    ArtifactoryUtils.resolveInputStream(inputStream, destinationFile);
                } catch (Exception e) {
                    Throwables.propagate(e);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
            IOUtils.closeQuietly(response.body().byteStream());
        } else {
            Payload payload = newInputStreamPayload(response.body().byteStream());
            contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
            builder.payload(payload);
        }
    }

    builder.headers(filterOutContentHeaders(headers));
    return builder.build();
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);/*  w  w w.  j  av  a 2s  .c  o m*/
    }

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

private @Nullable MultipartBuilder constructMultipartBody(ReadableArray body, String contentType,
        Callback callback) {/*ww  w .j  a v  a 2 s . co m*/
    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MediaType.parse(contentType));

    for (int i = 0, size = body.size(); i < size; i++) {
        ReadableMap bodyPart = body.getMap(i);

        // Determine part's content type.
        ReadableArray headersArray = bodyPart.getArray("headers");
        Headers headers = extractHeaders(headersArray, null);
        if (headers == null) {
            callback.invoke(0, null, "Missing or invalid header format for FormData part.");
            return null;
        }
        MediaType partContentType = null;
        String partContentTypeStr = headers.get(CONTENT_TYPE_HEADER_NAME);
        if (partContentTypeStr != null) {
            partContentType = MediaType.parse(partContentTypeStr);
            // Remove the content-type header because MultipartBuilder gets it explicitly as an
            // argument and doesn't expect it in the headers array.
            headers = headers.newBuilder().removeAll(CONTENT_TYPE_HEADER_NAME).build();
        }

        if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) {
            String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING);
            multipartBuilder.addPart(headers, RequestBody.create(partContentType, bodyValue));
        } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) {
            if (partContentType == null) {
                callback.invoke(0, null, "Binary FormData part needs a content-type header.");
                return null;
            }
            String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI);
            InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(),
                    fileContentUriStr);
            if (fileInputStream == null) {
                callback.invoke(0, null, "Could not retrieve file for uri " + fileContentUriStr);
                return null;
            }
            multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream));
        } else {
            callback.invoke(0, null, "Unrecognized FormData part.");
        }
    }
    return multipartBuilder;
}

From source file:com.facebook.react.modules.network.NetworkingModuleTest.java

License:Open Source License

@Test
public void testHeaders() throws Exception {
    OkHttpClient httpClient = mock(OkHttpClient.class);
    when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
        @Override/*from w ww  . j a  v  a  2 s.c  o  m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Call callMock = mock(Call.class);
            return callMock;
        }
    });
    NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);

    List<JavaOnlyArray> headers = Arrays.asList(JavaOnlyArray.of("Accept", "text/plain"),
            JavaOnlyArray.of("User-Agent", "React test agent/1.0"));

    networkingModule.sendRequest(mock(ExecutorToken.class), "GET", "http://someurl/baz", 0,
            JavaOnlyArray.from(headers), null, true, 0);
    ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
    verify(httpClient).newCall(argumentCaptor.capture());
    Headers requestHeaders = argumentCaptor.getValue().headers();
    assertThat(requestHeaders.size()).isEqualTo(2);
    assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain");
    assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0");
}

From source file:com.facebook.react.modules.network.NetworkingModuleTest.java

License:Open Source License

@Test
public void testMultipartPostRequestHeaders() throws Exception {
    PowerMockito.mockStatic(RequestBodyUtil.class);
    when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
            .thenReturn(mock(InputStream.class));
    when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
            .thenReturn(mock(RequestBody.class));

    List<JavaOnlyArray> headers = Arrays.asList(JavaOnlyArray.of("Accept", "text/plain"),
            JavaOnlyArray.of("User-Agent", "React test agent/1.0"),
            JavaOnlyArray.of("content-type", "multipart/form-data"));

    JavaOnlyMap body = new JavaOnlyMap();
    JavaOnlyArray formData = new JavaOnlyArray();
    JavaOnlyMap bodyPart = new JavaOnlyMap();
    bodyPart.putString("string", "value");
    bodyPart.putArray("headers",
            JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "name"))));
    formData.pushMap(bodyPart);/* ww w.  j a  va  2  s  .  co  m*/
    body.putArray("formData", formData);

    OkHttpClient httpClient = mock(OkHttpClient.class);
    when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Call callMock = mock(Call.class);
            return callMock;
        }
    });

    NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);
    networkingModule.sendRequest(mock(ExecutorToken.class), "POST", "http://someurl/uploadFoo", 0,
            JavaOnlyArray.from(headers), body, true, 0);

    // verify url, method, headers
    ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
    verify(httpClient).newCall(argumentCaptor.capture());
    assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo");
    assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
    assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo(MultipartBuilder.FORM.type());
    assertThat(argumentCaptor.getValue().body().contentType().subtype())
            .isEqualTo(MultipartBuilder.FORM.subtype());
    Headers requestHeaders = argumentCaptor.getValue().headers();
    assertThat(requestHeaders.size()).isEqualTo(3);
    assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain");
    assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0");
    assertThat(requestHeaders.get("content-type")).isEqualTo("multipart/form-data");
}

From source file:com.inductiveautomation.ignition.examples.reporting.datasource.common.RestJsonDataSource.java

/**
 * Attempts to connect to a Url using {@link OkHttpClient} and return the body of the reply as a String, if it is
 * JSON mime type.//from   w ww .  j av a  2  s. c  o  m
 * @param url String specifying the
 * @return the body of the http response received from the specified Url
 */
private String collectData(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();

    // get headers to check the content type out of
    Headers headers = null;
    if (response != null) {
        headers = response.headers();
    }

    // at least try to make sure we have JSON data.
    boolean isJSON = false;
    if (headers != null) {
        isJSON = MediaType.parse(headers.get("Content-Type")).equals(JSON);
    }

    return isJSON ? response.body().string() : "";
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

/**
 * Process the response data//from w ww  .  j  a  va 2s .  co  m
 */
private void processResponse(byte[] bResponse, long startTime, long endTime, BaseRequest request,
        String message, int httpCode, Headers headers) {
    BaseResponse response = request.getResponse();
    try {
        if (response == null) {
            // Get response header information
            String contentType = headers.get("ContentType");
            if (StringUtils.isBlank(contentType)) {
                contentType = "";
            }
            response = TankHttpUtil.newResponseObject(contentType);
            request.setResponse(response);
        }

        // Get response detail information
        response.setHttpMessage(message);
        response.setHttpCode(httpCode);

        // Get response header information
        for (String key : headers.names()) {
            response.setHeader(key, headers.get(key));
        }

        if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) {
            for (HttpCookie cookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore()
                    .getCookies()) {
                // System.out.println("in processResponse-getCookies");
                // System.out.println(cookie.toString());
                response.setCookie(cookie.getName(), cookie.getValue());
            }
        }

        response.setResponseTime(endTime - startTime);
        String contentType = response.getHttpHeader("Content-Type");
        String contentEncode = response.getHttpHeader("Content-Encoding");
        if (BaseResponse.isDataType(contentType) && contentEncode != null
                && contentEncode.toLowerCase().contains("gzip")) {
            // decode gzip for data types
            try {
                GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(bResponse));
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                IOUtils.copy(in, out);
                bResponse = out.toByteArray();
            } catch (Exception e) {
                LOG.warn(request.getLogUtil().getLogMessage("cannot decode gzip stream: " + e,
                        LogEventType.System));
            }
        }
        response.setResponseBody(bResponse);

    } catch (Exception ex) {
        LOG.warn("Unable to get response: " + ex.getMessage());
    } finally {
        response.logResponse();
    }
}

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

License:Apache License

public Request toRequest() {
    Headers responseHeaders = Headers.of(headers);
    String contentType = responseHeaders.get("Content-Type");
    return new Request.Builder().url(url).method(method, RequestBody.create(MediaType.parse(contentType), body))
            .headers(responseHeaders).build();
}

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();
}