List of usage examples for com.squareup.okhttp Headers size
public int size()
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java
License:Open Source License
private void testSyncTablePullOperationsFeatureHeader(OfflineTableTestOperation operation, final String expectedFeaturesHeader) { MobileServiceClient client = null;/* w w w .j av a 2 s . c o m*/ try { client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } 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) { boolean isFirstPage = request.getUrl().contains("$skip=0"); 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 (isFirstPage) { 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 + "]"; } } 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()); } }
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java
License:Open Source License
private void testOpportunisticConcurrencyOperationsFeatureHeader( OpportunisticConcurrencyTestOperation operation, final String expectedFeaturesHeader) { MobileServiceClient client = null;/*from w w w. j av a2s . c om*/ try { client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } 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 = "{\"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 + "]"; } 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(); 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.moesif.android.okhttp2.MoesifOkHttp2Stack.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); client.networkInterceptors().add(new MoesifOkHttp2Interceptor()); 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)); }// www . j av a 2 s .c om 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.peach.masktime.module.net.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(); LogUtils.i(TAG, "timeoutMs = " + timeoutMs); client.setProxy(Proxy.NO_PROXY); 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.ja v a 2s . c om*/ 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.phattn.vnexpressnews.io.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 www .j a v 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, length = responseHeaders.size(); i < length; i++) { final String name = responseHeaders.name(i); final String value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
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 . ja va 2 s .c o m 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.ydh.gva.util.net.volley.toolbox.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(); okHttpRequestBuilder.addHeader("clientos", "101"); okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + ""); okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + ""); okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + ""); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from www .j a v 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:feign.okhttp.OkHttpClient.java
License:Apache License
private static Map<String, Collection<String>> toMap(Headers headers) { Map<String, Collection<String>> result = new LinkedHashMap<String, Collection<String>>(headers.size()); for (String name : headers.names()) { // TODO: this is very inefficient as headers.values iterate case insensitively. result.put(name, headers.values(name)); }/*w ww .j a v a 2 s .c o m*/ return result; }
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 ww w . j a va2 s .c o m*/ 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
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE || (!slf4j.isDebugEnabled())) { return chain.proceed(request); }//w w w. j a va 2 s .com boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; try { 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() + ' ' + request.httpUrl() + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if (name.equalsIgnoreCase("authorization")) { log(name + ": ************"); } else { // Skip headers from the request body as they are // explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { log(name + ": " + headers.value(i)); } } } if (!logBody || !hasRequestBody) { slf4j.debug("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } log(""); String body = redactRequestBody(buffer.readString(charset)); log(body); log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace } long startNs = System.nanoTime(); Response response = chain.proceed(request); try { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); 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++) { log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { log("<-- END HTTP"); } else if (!isResponseBodyPrintable(response)) { log("<-- END HTTP (body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(maxPrintableBodySize); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() != 0) { log(""); log(redactResponseBody(buffer.clone().readString(charset))); } log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString()); } return response; }