Example usage for com.squareup.okhttp Headers size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of field values.

Usage

From source file:com.ichg.service.volley.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from   w  w w.  j av  a  2  s. co m
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

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

License:Apache License

protected void parseHeaders(Headers header) {
    if (null != header) {
        List<String> headerList = new ArrayList<>();
        for (int i = 0; i < header.size(); i++) {
            if (!header.name(i).startsWith("X-Jersey-Tracing")) {
                headerList.add(header.name(i));
                headerList.add(header.value(i));
            }/*  w ww . j av  a2s .com*/
        }

        headers = headerList.toArray(new String[headerList.size()]);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.framework.filters.HttpMetaEchoFilter.java

License:Open Source License

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

    JsonObject jResponse = new JsonObject();

    jResponse.addProperty("method", request.getMethod());

    Headers headers = request.getHeaders();
    if (headers != null && headers.size() > 0) {
        JsonObject jHeaders = new JsonObject();

        for (int i = 0; i < headers.size(); i++) {
            jHeaders.addProperty(headers.name(i), headers.value(i));
        }//from w ww .j a  v a 2  s . co m

        jResponse.add("headers", jHeaders);
    }

    Uri uri = Uri.parse(request.getUrl());
    String query = uri.getQuery();

    if (query != null && query.trim() != "") {
        JsonObject jParameters = new JsonObject();

        for (String parameter : query.split("&")) {
            jParameters.addProperty(parameter.split("=")[0], parameter.split("=")[1]);
        }
        jResponse.add("parameters", jParameters);
    }

    ServiceFilterResponseMock response = new ServiceFilterResponseMock();
    response.setContent(jResponse.toString());
    response.setStatus(new StatusLine(Protocol.HTTP_2, 200, ""));

    ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
    return nextServiceFilterCallback.onNext(requestMock);

    //return nextServiceFilterCallback.onNext(request);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.LoginTests.java

License:Open Source License

public void testAuthenticatedRequest() throws Throwable {
    final MobileServiceUser user = new MobileServiceUser("dummyUser");
    user.setAuthenticationToken("123abc");

    // Create client
    MobileServiceClient client = null;/*from ww w.j  a v  a 2 s  . c o m*/
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
        client.setCurrentUser(user);
    } catch (MalformedURLException e) {
    }

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

            int headerIndex = -1;

            Headers headers = request.getHeaders();
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i) == "X-ZUMO-AUTH") {
                    headerIndex = i;
                }
            }
            if (headerIndex == -1) {
                Assert.fail();
            }

            assertEquals(user.getAuthenticationToken(), headers.value(headerIndex));

            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setContent("{}");

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

            resultFuture.set(response);

            return resultFuture;
        }
    });

    client.getTable("dummy").execute().get();
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceClientTests.java

License:Open Source License

public void testOperationShouldAddHeaders() throws Throwable {

    // Create client
    MobileServiceClient client = null;/*from  w  w w .  j a va 2 s.c o m*/
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

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

            int zumoInstallationHeaderIndex = -1;
            int zumoApiVersionHeader = -1;
            int zumoVersionHeader = -1;
            int userAgentHeaderIndex = -1;
            int acceptHeaderIndex = -1;
            int acceptEncodingHeaderIndex = -1;

            String installationHeader = "X-ZUMO-INSTALLATION-ID";
            String apiVersionHeader = "ZUMO-API-VERSION";
            String versionHeader = "X-ZUMO-VERSION";
            String userAgentHeader = "User-Agent";
            String acceptHeader = "Accept";
            String acceptEncodingHeader = "Accept-Encoding";
            String versionNumber = "3.0.0";
            String apiVersionNumber = "2.0.0";

            Headers headers = request.getHeaders();
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i) == installationHeader) {
                    zumoInstallationHeaderIndex = i;
                } else if (headers.name(i) == apiVersionHeader) {
                    zumoApiVersionHeader = i;
                } else if (headers.name(i) == versionHeader) {
                    zumoVersionHeader = i;
                } else if (headers.name(i) == userAgentHeader) {
                    userAgentHeaderIndex = i;
                } else if (headers.name(i) == acceptHeader) {
                    acceptHeaderIndex = i;
                } else if (headers.name(i) == acceptEncodingHeader) {
                    acceptEncodingHeaderIndex = i;
                }
            }

            if (zumoInstallationHeaderIndex == -1) {
                resultFuture.setException(new Exception("zumoInstallationHeaderIndex == -1"));
                return resultFuture;
            }
            if (zumoApiVersionHeader == -1) {
                resultFuture.setException(new Exception("zumoApiVersionHeader == -1"));
                return resultFuture;
            }
            if (zumoVersionHeader == -1) {
                resultFuture.setException(new Exception("zumoVersionHeader == -1"));
                return resultFuture;
            }
            if (userAgentHeaderIndex == -1) {
                resultFuture.setException(new Exception("userAgentHeaderIndex == -1"));
                return resultFuture;
            }
            if (acceptHeaderIndex == -1) {
                resultFuture.setException(new Exception("acceptHeaderIndex == -1"));
                return resultFuture;
            }
            if (acceptEncodingHeaderIndex == -1) {
                resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1"));
                return resultFuture;
            }

            String expectedUserAgent = String.format(
                    "ZUMO/%s (lang=%s; os=%s; os_version=%s; arch=%s; version=%s)", "1.0", "Java", "Android",
                    Build.VERSION.RELEASE, Build.CPU_ABI, versionNumber);

            if (headers.value(zumoInstallationHeaderIndex) == null) {
                resultFuture.setException(new Exception("headers[zumoInstallationHeaderIndex] == null"));
                return resultFuture;
            }

            if (!apiVersionNumber.equals(headers.value(zumoApiVersionHeader))) {
                resultFuture.setException(new Exception("expectedAppKey != headers[zumoApiVersionHeader]"));
                return resultFuture;
            }

            if (!expectedUserAgent.equals(headers.value(userAgentHeaderIndex))) {
                resultFuture.setException(new Exception("expectedUserAgent != headers[userAgentHeaderIndex]"));
                return resultFuture;
            }

            if (!versionNumber.equals(headers.value(zumoVersionHeader))) {
                resultFuture.setException(new Exception(versionNumber + "!= headers[zumoVersionHeader]"));
                return resultFuture;
            }

            if (!"application/json".equals(headers.value(acceptHeaderIndex))) {
                resultFuture.setException(new Exception("application/json != headers[acceptHeaderIndex]"));
                return resultFuture;
            }

            if (!"gzip".equals(headers.value(acceptEncodingHeaderIndex))) {
                resultFuture.setException(new Exception("gzip != headers[acceptEncodingHeaderIndex]"));
                return resultFuture;
            }

            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setContent("{}");

            resultFuture.set(response);

            return resultFuture;
        }
    });

    try {
        client.getTable("dummy").execute().get();
    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            fail(exception.getCause().getMessage());
        } else {
            fail(exception.getMessage());
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceClientTests.java

License:Open Source License

public void testInsertUpdateShouldAddContentTypeJson() throws Throwable {

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

    // Create client
    MobileServiceClient client = null;//from   w  ww.j a v a2  s.  c  o  m
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

            Headers headers = request.getHeaders();

            boolean headerPresent = false;
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i).equals(HttpConstants.ContentType)
                        && headers.value(i).equals("application/json")) {
                    headerPresent = true;
                }
            }

            if (!headerPresent) {
                resultFuture.setException(new Exception("!headerPresent"));
                return resultFuture;
            }

            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setContent("{}");

            resultFuture.set(response);

            return resultFuture;
        }
    });

    try {
        JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("someValue", 42);

        client.getTable("dummy").insert(jsonObject).get();

        jsonObject.addProperty("id", 1);

        client.getTable("dummy").update(jsonObject).get();
    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            fail(exception.getCause().getMessage());
        } else {
            fail(exception.getMessage());
        }
    }

}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceClientTests.java

License:Open Source License

public void testDeleteQueryShouldNotAddContentTypeJson() throws Throwable {

    // Create client
    MobileServiceClient client = null;//from w w  w  . j  av  a2 s  . c o m
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

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

            Headers headers = request.getHeaders();

            boolean headerPresent = false;
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i).equals(HttpConstants.ContentType)
                        && headers.value(i).equals("application/json")) {
                    headerPresent = true;
                }
            }

            if (headerPresent) {
                resultFuture.setException(new Exception("!headerPresent"));
                return resultFuture;
            }

            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setContent("{}");

            resultFuture.set(response);

            return resultFuture;
        }
    });

    try {
        client.getTable("dummy").delete(42).get();

        client.getTable("dummy").execute().get();
    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            fail(exception.getCause().getMessage());
        } else {
            fail(exception.getMessage());
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

License:Open Source License

private void testTableFeatureHeader(TableTestOperation operation, final boolean responseIsArray,
        final String expectedFeaturesHeader) {
    MobileServiceClient client = null;/*from  w ww.ja  va2s .  c o m*/
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
            String featuresHeaderName = "X-ZUMO-FEATURES";

            Headers headers = request.getHeaders();
            String features = null;
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i) == featuresHeaderName) {
                    features = headers.value(i);
                }
            }

            if (features == null) {
                resultFuture.setException(new Exception("No " + featuresHeaderName + " header on API call"));
            } else if (!features.equals(expectedFeaturesHeader)) {
                resultFuture.setException(new Exception("Incorrect features header; expected "
                        + expectedFeaturesHeader + ", actual " + features));
            } else {
                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                String content = "{\"id\":\"the-id\",\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":33}";
                if (responseIsArray) {
                    content = "[" + content + "]";
                }
                response.setContent(content);
                resultFuture.set(response);
            }

            return resultFuture;
        }
    });

    try {
        MobileServiceTable<PersonTestObjectWithStringId> typedTable = client
                .getTable(PersonTestObjectWithStringId.class);
        MobileServiceJsonTable jsonTable = client.getTable("Person");
        operation.executeOperation(typedTable, jsonTable);
    } catch (Exception exception) {
        Throwable ex = exception;
        while (ex instanceof ExecutionException || ex instanceof MobileServiceException) {
            ex = ex.getCause();
        }
        ex.printStackTrace();
        fail(ex.getMessage());
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

License:Open Source License

private void testInvokeApiFeatureHeader(ClientTestOperation operation, final String expectedFeaturesHeader) {
    MobileServiceClient client = null;/*w  w  w  .  j a v  a2  s .co  m*/
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
            String featuresHeaderName = "X-ZUMO-FEATURES";

            Headers headers = request.getHeaders();
            String features = null;
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i) == featuresHeaderName) {
                    features = headers.value(i);
                }
            }

            if (features == null) {
                resultFuture.setException(new Exception("No " + featuresHeaderName + " header on API call"));
            } else if (!features.equals(expectedFeaturesHeader)) {
                resultFuture.setException(new Exception("Incorrect features header; expected "
                        + expectedFeaturesHeader + ", actual " + features));
            } else {
                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                response.setContent("{}");
                resultFuture.set(response);
            }

            return resultFuture;
        }
    });

    try {
        operation.executeOperation(client);
    } catch (Exception exception) {
        Throwable ex = exception;
        while (ex instanceof ExecutionException || ex instanceof MobileServiceException) {
            ex = ex.getCause();
        }
        fail(ex.getMessage());
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

License:Open Source License

private void testSyncTableOperationsFeatureHeader(OfflineTableTestOperation operation,
        final String expectedFeaturesHeader) {
    MobileServiceClient client = null;/* w w w .  j  a v a 2  s.  com*/
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    boolean fistPullPage = false;

    MobileServiceLocalStoreMock store = new MobileServiceLocalStoreMock();
    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

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

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
            String featuresHeaderName = "X-ZUMO-FEATURES";

            Headers headers = request.getHeaders();
            String features = null;
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i) == featuresHeaderName) {
                    features = headers.value(i);
                }
            }

            if (features == null) {
                resultFuture.setException(new Exception("No " + featuresHeaderName + " header on API call"));
            } else if (!features.equals(expectedFeaturesHeader)) {
                resultFuture.setException(new Exception("Incorrect features header; expected "
                        + expectedFeaturesHeader + ", actual " + features));
            } else {
                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                Uri requestUri = Uri.parse(request.getUrl());

                String content = "[]";

                //if (fistPullPage) {
                content = "{\"id\":\"the-id\",\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":33}";

                if (request.getMethod().equalsIgnoreCase(HttpConstants.GetMethod)
                        && requestUri.getPathSegments().size() == 2) {
                    // GET which should return an array of results
                    content = "[" + content + "]";
                }

                //fistPullPage = false;
                //}

                response.setContent(content);
                resultFuture.set(response);
            }

            return resultFuture;
        }
    });

    try {
        Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
        tableDefinition.put("id", ColumnDataType.String);
        tableDefinition.put("firstName", ColumnDataType.String);
        tableDefinition.put("lastName", ColumnDataType.String);
        tableDefinition.put("age", ColumnDataType.Integer);
        store.defineTable("Person", tableDefinition);

        client.getSyncContext().initialize(store, new SimpleSyncHandler()).get();

        MobileServiceSyncTable<PersonTestObjectWithStringId> typedTable = client
                .getSyncTable(PersonTestObjectWithStringId.class);
        MobileServiceJsonSyncTable jsonTable = client.getSyncTable("Person");
        operation.executeOperation(client, typedTable, jsonTable);
    } catch (Exception exception) {
        Throwable ex = exception;
        while (ex instanceof ExecutionException || ex instanceof MobileServiceException) {
            ex = ex.getCause();
        }
        fail(ex.getMessage());
    }
}