List of usage examples for com.squareup.okhttp Protocol HTTP_1_1
Protocol HTTP_1_1
To view the source code for com.squareup.okhttp Protocol HTTP_1_1.
Click Source Link
From source file:com.planyourexchange.utils.TokenManagerTest.java
License:Open Source License
@Test(timeout = 1000) public void test_authenticate_before_success() throws Exception { final TokenManager tokenManager = new TokenManager(sharedPreferences); final AuthToken authToken = new AuthToken(); authToken.setToken("NICE TOKEN"); final Response response = new Response.Builder().protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://api.example.com").build()).code(404).build(); tokenManager.setTokenAction(new TokenManager.TokenAction() { @Override//from www.j a v a 2 s.co m public void newToken() { new Thread(new Runnable() { @Override public void run() { tokenManager.success(authToken, null); } }).start(); } }); new Thread(new Runnable() { @Override public void run() { try { Request result = tokenManager.authenticate(null, response); String header = result.header(AUTHORIZATION); assertEquals(TOKEN + authToken.getToken(), header); } catch (IOException e) { fail("Couldn't Authenticate"); } synchronized (LOCK) { LOCK.notifyAll(); } } }).start(); synchronized (LOCK) { LOCK.wait(); } }
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); }/* ww w . ja v a 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.shopify.buy.data.MockResponder.java
License:Open Source License
@Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); String key = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement()); JsonElement element = data.get(key); JsonObject responseJson = element.getAsJsonObject(); int code = responseJson.get(KEY_CODE).getAsInt(); String message = responseJson.get(KEY_MESSAGE).getAsString(); String body = responseJson.get(KEY_BODY).getAsString(); if (code >= 400) { retrofit.client.Response retrofitResponse = new retrofit.client.Response(request.urlString(), code, "reason", Collections.EMPTY_LIST, new TypedString(body)); throw RetrofitError.httpError(request.urlString(), retrofitResponse, null, null); }//from w w w .jav a 2 s.com MediaType contentType = MediaType.parse("application/json; charset=utf-8"); return new Response.Builder().protocol(Protocol.HTTP_1_1).code(code).request(request) .body(ResponseBody.create(contentType, body)).message(message).addHeader("key", "value").build(); }
From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java
License:Apache License
/** * Constructor./*from w ww.j a v a2 s . co m*/ * @param metricsServer */ public HawkularMetricsClient(URL metricsServer) { this.serverUrl = metricsServer; httpClient = new OkHttpClient(); httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS); httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS); httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS); httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); httpClient.setProxySelector(ProxySelector.getDefault()); httpClient.setCookieHandler(CookieHandler.getDefault()); httpClient.setCertificatePinner(CertificatePinner.DEFAULT); httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE); httpClient.setConnectionPool(ConnectionPool.getDefault()); httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1)); httpClient.setConnectionSpecs(DEFAULT_CONNECTION_SPECS); httpClient.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(httpClient, Network.DEFAULT); }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client// www .j a v a2 s . com */ private OkHttpClient createHttpClient() { OkHttpClient client = new OkHttpClient(); client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS); client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS); client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS); client.setFollowRedirects(connectorOptions.isFollowRedirects()); client.setFollowSslRedirects(connectorOptions.isFollowRedirects()); client.setProxySelector(ProxySelector.getDefault()); client.setCookieHandler(CookieHandler.getDefault()); client.setCertificatePinner(CertificatePinner.DEFAULT); client.setAuthenticator(AuthenticatorAdapter.INSTANCE); client.setConnectionPool(ConnectionPool.getDefault()); client.setProtocols(Util.immutableList(Protocol.HTTP_1_1)); client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS); client.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(client, Network.DEFAULT); return client; }
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); }/*from w ww . ja v a 2s. 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; }
From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.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); }//from w ww .ja v a2 s . c o m boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; UUID requestId = UUID.randomUUID(); StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n') .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol); if (!logHeaders && requestBody != null) { requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)"); } requestMessage.append('\n'); if (logHeaders) { if (requestBody != null) { // 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) { requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n'); } if (requestBody.contentLength() != -1) { requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n'); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name) || "Proxy-Authorization".equalsIgnoreCase(name) || "WWW-Authenticate".equalsIgnoreCase(name)) { requestMessage.append(name).append(": *****\n"); } // Skip headers from the request body as they are explicitly // logged above. else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { requestMessage.append(name).append(": ").append(headers.value(i)).append('\n'); } } if (!logBody || requestBody == null) { requestMessage.append("--> END ").append(requestId).append('\n'); } else if (bodyEncoded(request.headers())) { requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n'); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } requestMessage.append('\n'); if (isPlaintext(buffer)) { requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId) .append(" (").append(requestBody.contentLength()).append("-byte body)\n"); } else { requestMessage.append("--> END ").append(requestId).append(" (binary ") .append(requestBody.contentLength()).append("-byte body omitted)\n"); } } } logger.log(requestMessage.substring(0, requestMessage.length() - 1)); long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- " + requestId + "HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ') .append(response.request().url()).append(" (").append(tookMs).append("ms"); if (!logHeaders) { responseMessage.append(", "); if (contentLength != -1) { responseMessage.append(contentLength).append("-byte"); } else { responseMessage.append("unknown-length"); } responseMessage.append(" body"); } responseMessage.append(")\n"); responseMessage.append(response.code()).append(' ').append(response.message()).append('\n'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n'); } if (!logBody || !HttpEngine.hasBody(response)) { responseMessage.append("<-- END HTTP\n"); } else if (bodyEncoded(response.headers())) { responseMessage.append("<-- END HTTP (encoded body omitted)\n"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (!isPlaintext(buffer)) { responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size()) .append("-byte body omitted)"); logger.log(responseMessage.toString()); return response; } if (contentLength != 0) { responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n'); } responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n"); } } logger.log(responseMessage.substring(0, responseMessage.length() - 1)); return response; }
From source file:org.floens.chan.core.cache.FileCache.java
License:Open Source License
public FileCache(File directory, long maxSize, String userAgent) { this.directory = directory; this.maxSize = maxSize; this.userAgent = userAgent; httpClient = new OkHttpClient(); httpClient.setConnectTimeout(TIMEOUT, TimeUnit.MILLISECONDS); httpClient.setReadTimeout(TIMEOUT, TimeUnit.MILLISECONDS); httpClient.setWriteTimeout(TIMEOUT, TimeUnit.MILLISECONDS); // Disable SPDY, causes reproducible timeouts, only one download at the same time and other fun stuff httpClient.setProtocols(Collections.singletonList(Protocol.HTTP_1_1)); makeDir();//from w ww . j a v a 2 s . c o m calculateSize(); }
From source file:pct.droid.base.providers.media.YTSProvider.java
License:Open Source License
@Override protected OkHttpClient getClient() { OkHttpClient client = super.getClient().clone(); // Use only HTTP 1.1 for YTS List<Protocol> proto = new ArrayList<>(); proto.add(Protocol.HTTP_1_1); client.setProtocols(proto);//from w w w . ja va 2 s.c o m return client; }
From source file:retrofit.KOkHttpCall.java
License:Apache License
private Response<T> execCacheRequest(Request request) { if (responseConverter instanceof KGsonConverter) { KGsonConverter<T> converter = (KGsonConverter<T>) responseConverter; Cache cache = converter.getCache(); if (cache == null) { return null; }//from w w w . jav a 2 s . c om Entry entry = cache.get(request.urlString());// ?entry if (entry != null && entry.data != null) {// ? MediaType contentType = MediaType.parse(entry.mimeType); byte[] bytes = entry.data; try { com.squareup.okhttp.Response rawResponse = new com.squareup.okhttp.Response.Builder()// .code(200).request(request).protocol(Protocol.HTTP_1_1) .body(ResponseBody.create(contentType, bytes)).build(); return parseResponse(rawResponse, request); } catch (Exception e) { e.printStackTrace(); } } } return null; }