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:com.maxleapmobile.gitmaster.ui.fragment.MineFragment.java

License:Open Source License

private void getStarCount() {
    ApiManager.getInstance().countStar(mUsername, new ApiCallback<retrofit.Response<ResponseBody>>() {
        @Override//from   w ww .  j  a v  a  2 s . c  o m
        public void onSuccess(retrofit.Response<ResponseBody> response) {
            Headers headers = response.headers();
            String link = headers.get("Link");
            PageLinks pageLinks = new PageLinks(link);
            mUserinfoBinding.setPagelinks(pageLinks);
        }

        @Override
        public void onFail(Throwable throwable) {

        }
    });
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable.java

License:Open Source License

private String getHeaderValue(Headers headers, String headerName) {

    if (headers == null) {
        return null;
    }/* w  ww.  jav a  2s.  c o  m*/

    return headers.get(headerName);
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.MiscTests.java

License:Open Source License

public MiscTests() {
    super("Misc tests");

    this.addTest(createFilterTestWithMultipleRequests(true));
    this.addTest(createFilterTestWithMultipleRequests(false));

    TestCase withFilterDoesNotChangeTheClient = new TestCase() {

        @Override/*from   w w w.j av a2  s  .c om*/
        protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {
            final TestResult testResult = new TestResult();
            testResult.setTestCase(this);
            testResult.setStatus(TestStatus.Passed);
            final TestCase testCase = this;
            client.withFilter(new ServiceFilter() {

                @Override
                public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                        NextServiceFilterCallback nextServiceFilterCallback) {
                    log("executed filter triggering failure");
                    testResult.setStatus(TestStatus.Failed);

                    return nextServiceFilterCallback.onNext(request);
                }
            });

            log("execute query");

            try {

                client.getTable(ROUND_TRIP_TABLE_NAME).top(5).execute().get();
            } catch (Exception exception) {
                createResultFromException(testResult, exception);
            }

            if (callback != null)
                callback.onTestComplete(testCase, testResult);
        }

    };
    withFilterDoesNotChangeTheClient.setName("Verify that 'withFilter' does not change the client");
    this.addTest(withFilterDoesNotChangeTheClient);

    TestCase bypassTest = new TestCase() {

        @Override
        protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {

            final TestCase testCase = this;
            final TestResult result = new TestResult();
            result.setStatus(TestStatus.Passed);
            result.setTestCase(this);

            final String json = "{'id':1,'name':'John Doe','age':33}".replace('\'', '\"');
            MobileServiceClient filtered = client.withFilter(new ServiceFilter() {

                @Override
                public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                        NextServiceFilterCallback nextServiceFilterCallback) {

                    final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

                    // ListenableFuture<ServiceFilterResponse> notifyFuture
                    // = nextServiceFilterCallback.onNext(request);
                    //
                    // Futures.addCallback(notifyFuture, new
                    // FutureCallback<ServiceFilterResponse>() {
                    //
                    // @Override
                    // public void onFailure(Throwable exception) {
                    // resultFuture.setException(exception);
                    // }
                    //
                    // @Override
                    // public void onSuccess(ServiceFilterResponse v) {
                    resultFuture.set(new MockResponse(json, 201));
                    // return;
                    // }
                    // });

                    return resultFuture;
                }
            });

            log("insert item");

            try {

                JsonObject jsonEntity = filtered.getTable("fakeTable").insert(new JsonObject()).get();

                JsonObject expectedObject = new JsonParser().parse(json).getAsJsonObject();
                log("verify items are equal");
                if (!Util.compareJson(expectedObject, jsonEntity)) {
                    createResultFromException(result, new ExpectedValueException(expectedObject, jsonEntity));
                }
            } catch (Exception exception) {

                createResultFromException(result, exception);
            } finally {
                if (callback != null)
                    callback.onTestComplete(testCase, result);
            }
        }
    };

    bypassTest.setName("Filter to bypass service");
    this.addTest(bypassTest);

    this.addTest(createParameterPassingTest(true));
    this.addTest(createParameterPassingTest(false));

    this.addTest(createHttpContentApiTest());

    this.addTest(new TestCase("User-Agent validation") {

        @Override
        protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {
            final TestCase testCase = this;
            final TestResult testResult = new TestResult();
            testResult.setTestCase(testCase);
            testResult.setStatus(TestStatus.Failed);
            client = client.withFilter(new ServiceFilter() {

                public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                        NextServiceFilterCallback nextServiceFilterCallback) {

                    final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

                    Headers headers = request.getHeaders();

                    String userAgent = headers.get("User-Agent");

                    if (userAgent != null) {
                        log("User-Agent: " + userAgent);
                        testResult.setStatus(TestStatus.Passed);
                        String clientVersion = userAgent;
                        if (clientVersion.endsWith(")")) {
                            clientVersion = clientVersion.substring(0, clientVersion.length() - 1);
                        }
                        int indexOfEquals = clientVersion.lastIndexOf('=');
                        if (indexOfEquals >= 0) {
                            clientVersion = clientVersion.substring(indexOfEquals + 1);
                            Util.getGlobalTestParameters().put(ClientVersionKey, clientVersion);
                        }
                    }

                    ListenableFuture<ServiceFilterResponse> notifyFuture = nextServiceFilterCallback
                            .onNext(request);

                    Futures.addCallback(notifyFuture, new FutureCallback<ServiceFilterResponse>() {

                        @Override
                        public void onFailure(Throwable exception) {
                        }

                        @Override
                        public void onSuccess(ServiceFilterResponse response) {
                            if (response != null) {

                                Headers headers = response.getHeaders();

                                String runtimeVersion = headers.get("x-zumo-version");

                                if (runtimeVersion != null) {
                                    Util.getGlobalTestParameters().put(ServerVersionKey, runtimeVersion);
                                }
                            }

                            resultFuture.set(response);

                        }
                    });

                    return resultFuture;
                }
            });

            log("execute query to activate filter");

            try {

                client.getTable(ROUND_TRIP_TABLE_NAME).top(5).execute().get();
            } catch (Exception exception) {
                createResultFromException(testResult, exception);
            } finally {

                if (callback != null)
                    callback.onTestComplete(testCase, testResult);
            }
        }
    });
}

From source file:com.parse.ParseHttpClientTest.java

License:Open Source License

private void doSingleParseHttpClientExecuteWithResponse(int responseCode, String responseStatus,
        String responseContent, ParseHttpClient client) throws Exception {
    MockWebServer server = new MockWebServer();

    // Make mock response
    int responseContentLength = responseContent.length();
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus)
            .setBody(responseContent);/*  w w w  . j a va2 s  . co m*/

    // Start mock server
    server.enqueue(mockResponse);
    server.start();

    // Make ParseHttpRequest
    Map<String, String> requestHeaders = new HashMap<>();
    requestHeaders.put("User-Agent", "Parse Android SDK");

    String requestUrl = server.getUrl("/").toString();
    JSONObject json = new JSONObject();
    json.put("key", "value");
    String requestContent = json.toString();
    int requestContentLength = requestContent.length();
    String requestContentType = "application/json";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl)
            .setMethod(ParseHttpRequest.Method.POST)
            .setBody(new ParseByteArrayHttpBody(requestContent, requestContentType)).setHeaders(requestHeaders)
            .build();

    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);

    RecordedRequest recordedApacheRequest = server.takeRequest();

    // Verify request method
    assertEquals(ParseHttpRequest.Method.POST.toString(), recordedApacheRequest.getMethod());

    // Verify request headers, since http library automatically adds some headers, we only need to
    // verify all parseRequest headers are in recordedRequest headers.
    Headers recordedApacheHeaders = recordedApacheRequest.getHeaders();
    Set<String> recordedApacheHeadersNames = recordedApacheHeaders.names();
    for (String name : parseRequest.getAllHeaders().keySet()) {
        assertTrue(recordedApacheHeadersNames.contains(name));
        assertEquals(parseRequest.getAllHeaders().get(name), recordedApacheHeaders.get(name));
    }

    // Verify request body
    assertEquals(requestContentLength, recordedApacheRequest.getBodySize());
    assertArrayEquals(requestContent.getBytes(), recordedApacheRequest.getBody().readByteArray());

    // Verify response status code
    assertEquals(responseCode, parseResponse.getStatusCode());
    // Verify response status
    assertEquals(responseStatus, parseResponse.getReasonPhrase());
    // Verify all response header entries' keys and values are not null.
    for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
        assertNotNull(entry.getKey());
        assertNotNull(entry.getValue());
    }
    // Verify response body
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);
    // Verify response body size
    assertEquals(responseContentLength, content.length);

    // Shutdown mock server
    server.shutdown();
}

From source file:com.parse.ParseHttpClientTest.java

License:Open Source License

private void doSingleParseHttpClientExecuteWithGzipResponse(int responseCode, String responseStatus,
        final String responseContent, ParseHttpClient client) throws Exception {
    MockWebServer server = new MockWebServer();

    // Make mock response
    Buffer buffer = new Buffer();
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write(responseContent.getBytes());
    gzipOut.close();/*from   w  w  w. j  av  a  2s.  com*/
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus)
            .setBody(buffer).setHeader("Content-Encoding", "gzip");

    // Start mock server
    server.enqueue(mockResponse);
    server.start();

    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.getUrl("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl)
            .setMethod(ParseHttpRequest.Method.GET).build();

    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);

    RecordedRequest recordedRequest = server.takeRequest();

    // Verify request method
    assertEquals(ParseHttpRequest.Method.GET.toString(), recordedRequest.getMethod());

    // Verify request headers
    Headers recordedHeaders = recordedRequest.getHeaders();

    assertEquals("gzip", recordedHeaders.get("Accept-Encoding"));

    // Verify we do not have Content-Encoding header
    assertNull(parseResponse.getHeader("Content-Encoding"));

    // Verify response body
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);

    // Shutdown mock server
    server.shutdown();
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ok.HttpURLConnectionImpl.java

License:Apache License

private HttpEngine newHttpEngine(String method, Connection connection, RetryableSink requestBody,
        Response priorResponse) {
    // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
    RequestBody placeholderBody = HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null;
    Request.Builder builder = new Request.Builder().url(getURL()).method(method, placeholderBody);
    Headers headers = requestHeaders.build();
    for (int i = 0, size = headers.size(); i < size; i++) {
        builder.addHeader(headers.name(i), headers.value(i));
    }/*from w w  w . j  a v  a2s  .com*/

    boolean bufferRequestBody = false;
    if (HttpMethod.permitsRequestBody(method)) {
        // Specify how the request body is terminated.
        if (fixedContentLength != -1) {
            builder.header("Content-Length", Long.toString(fixedContentLength));
        } else if (chunkLength > 0) {
            builder.header("Transfer-Encoding", "chunked");
        } else {
            bufferRequestBody = true;
        }

        // Add a content type for the request body, if one isn't already present.
        if (headers.get("Content-Type") == null) {
            builder.header("Content-Type", "application/x-www-form-urlencoded");
        }
    }

    if (headers.get("User-Agent") == null) {
        builder.header("User-Agent", defaultUserAgent());
    }

    Request request = builder.build();

    // If we're currently not using caches, make sure the engine's client doesn't have one.
    OkHttpClient engineClient = client;
    if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) {
        engineClient = client.clone().setCache(null);
    }

    return new HttpEngine(engineClient, request, bufferRequestBody, true, false, connection, null, requestBody,
            priorResponse);
}

From source file:io.macgyver.core.okhttp.LoggingInterceptor.java

License:Apache License

private boolean bodyEncoded(Headers headers) {

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

From source file:io.minio.http.HeaderParser.java

License:Apache License

/**
 * Sets destination object from Headers object.
 *///from   w  w w.  j  av  a  2 s .c o  m
public static void set(Headers headers, Object destination) {

    Field[] publicFields;
    Field[] privateFields;
    Field[] fields;

    Class<?> cls = destination.getClass();
    publicFields = cls.getFields();
    privateFields = cls.getDeclaredFields();
    fields = new Field[publicFields.length + privateFields.length];
    System.arraycopy(publicFields, 0, fields, 0, publicFields.length);
    System.arraycopy(privateFields, 0, fields, publicFields.length, privateFields.length);

    for (Field field : fields) {
        Annotation annotation = field.getAnnotation(Header.class);
        if (annotation == null) {
            continue;
        }

        Header httpHeader = (Header) annotation;
        String value = httpHeader.value();
        String setter = httpHeader.setter();
        if (setter.isEmpty()) {
            // assume setter name as 'setFieldName'
            String name = field.getName();
            setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
        }

        try {
            Method setterMethod = cls.getMethod(setter, new Class[] { String.class });
            String valueString = headers.get(value);
            if (valueString != null) {
                setterMethod.invoke(destination, valueString);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | IllegalArgumentException e) {
            LOGGER.log(Level.SEVERE, "exception occured: ", e);
            LOGGER.log(Level.INFO, "setter: " + setter);
            LOGGER.log(Level.INFO, "annotation: " + value);
            LOGGER.log(Level.INFO, "value: " + headers.get(value));
        }
    }
}

From source file:io.minio.Signer.java

License:Apache License

private void setCanonicalHeaders() {
    this.canonicalHeaders = new TreeMap<>();

    Headers headers = this.request.headers();
    for (String name : headers.names()) {
        String signedHeader = name.toLowerCase();
        if (!IGNORED_HEADERS.contains(signedHeader)) {
            this.canonicalHeaders.put(signedHeader, headers.get(name));
        }//from ww  w  . j  av  a 2s.c o m
    }

    this.signedHeaders = Joiner.on(";").join(this.canonicalHeaders.keySet());
}

From source file:org.tinymediamanager.core.threading.DownloadTask.java

License:Apache License

@Override
protected void doInBackground() {
    try {//from ww w.  j ava 2  s . c  o m
        // verify the url is not empty and starts with at least
        if (StringUtils.isBlank(url) || !url.toLowerCase().startsWith("http")) {
            return;
        }

        // if file extension is empty, detect from url, or content type
        String ext = FilenameUtils.getExtension(file.getName());
        if (ext != null && ext.length() > 4) {
            ext = ""; // no extension when longer than 4 chars!
        }
        if (ext == null || ext.isEmpty()) {
            ext = UrlUtil.getExtension(url);
            if (!ext.isEmpty()) {
                if (Globals.settings.getAllSupportedFileTypes().contains("." + ext)) {
                    file = new File(file.getParent(), file.getName() + "." + ext);
                } else {
                    // unsupported filetype, eg php/asp/cgi script
                    ext = "";
                }
            }
        }

        LOGGER.info("Downloading " + url);
        StreamingUrl u = new StreamingUrl(UrlUtil.getURIEncoded(url).toASCIIString());
        if (StringUtils.isNotBlank(userAgent)) {
            u.setUserAgent(userAgent);
        }
        InputStream is = u.getInputStream();

        // trace server headers
        LOGGER.trace("Server returned: " + u.getStatusLine());
        Headers headers = u.getHeadersResponse();
        for (String name : headers.names()) {
            LOGGER.trace(" < " + name + ": " + headers.get(name));
        }

        if (u.isFault()) {
            MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, u.getUrl(), u.getStatusLine()));
            is.close();
            return;
        }

        long length = u.getContentLength();
        String type = u.getContentEncoding();
        if (ext.isEmpty()) {
            // still empty? try to parse from mime header
            if (type.startsWith("video/") || type.startsWith("audio/") || type.startsWith("image/")) {
                ext = type.split("/")[1];
                ext = ext.replaceAll("x-", ""); // x-wmf and others
                file = new File(file.getParent(), file.getName() + "." + ext);
            }
        }

        LOGGER.info("Downloading to " + file);

        File tempFile = new File(file.getAbsolutePath() + ".part");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
        FileOutputStream outputStream = new FileOutputStream(tempFile);
        int count = 0;
        byte buffer[] = new byte[2048];
        Long timestamp1 = System.nanoTime();
        Long timestamp2;
        long bytesDone = 0;
        long bytesDonePrevious = 0;
        double speed = 0;

        while ((count = bufferedInputStream.read(buffer, 0, buffer.length)) != -1) {
            if (cancel) {
                break;
            }

            outputStream.write(buffer, 0, count);
            bytesDone += count;

            // we push the progress only once per 250ms (to use less performance and get a better download speed)
            timestamp2 = System.nanoTime();
            if (timestamp2 - timestamp1 > 250000000) {
                // avg. speed between the actual and the previous
                speed = (speed
                        + (bytesDone - bytesDonePrevious) / ((double) (timestamp2 - timestamp1) / 1000000000))
                        / 2;

                timestamp1 = timestamp2;
                bytesDonePrevious = bytesDone;

                if (length > 0) {
                    publishState(formatBytesForOutput(bytesDone) + "/" + formatBytesForOutput(length) + " @"
                            + formatSpeedForOutput(speed), (int) (bytesDone * 100 / length));
                } else {
                    setWorkUnits(0);
                    publishState(formatBytesForOutput(bytesDone) + " @" + formatSpeedForOutput(speed), 0);
                }

            }
        }

        outputStream.close();

        // we must not close the input stream on cancel(the rest will be downloaded if we close it on cancel)
        if (!cancel) {
            is.close();
        }

        if (cancel) {
            // delete half downloaded file
            Utils.deleteFileSafely(tempFile);
        } else {
            if (ext.isEmpty()) {
                // STILL empty? hmpf...
                // now we have a chicken-egg problem:
                // MediaInfo needs MF type to correctly fetch extension
                // to detect MF type, we need the extension
                // so we are forcing to read the container type direct on tempFile
                MediaFile mf = new MediaFile(tempFile);
                mf.setContainerFormatDirect(); // force direct read of mediainfo - regardless of filename!!!
                ext = mf.getContainerFormat();
                if (!ext.isEmpty()) {
                    file = new File(file.getParent(), file.getName() + "." + ext);
                }
            }

            Utils.deleteFileSafely(file); // delete existing file
            boolean ok = Utils.moveFileSafe(tempFile, file);
            if (ok) {
                Utils.deleteFileSafely(tempFile);
                if (media != null) {
                    MediaFile mf = new MediaFile(file, fileType);
                    mf.gatherMediaInformation();
                    media.removeFromMediaFiles(mf); // remove old (possibly same) file
                    media.addToMediaFiles(mf); // add file, but maybe with other MI values
                    media.saveToDb();
                }
            } else {
                LOGGER.warn("Download to '" + tempFile + "' was ok, but couldn't move to '" + file + "'");
            }
        } // end isCancelled
    } catch (Exception e) {
        LOGGER.error("problem downloading: ", e);
    }
}