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:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Test public void applicationInterceptorsCanShortCircuitResponses() throws Exception { server.shutdown(); // Accept no connections. Request request = new Request.Builder().url("https://localhost:1/").build(); final Response interceptorResponse = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1) .code(200).message("Intercepted!") .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "abc")).build(); client.interceptors().add(new Interceptor() { @Override// ww w . j av a 2 s . c o m public Response intercept(Chain chain) throws IOException { return interceptorResponse; } }); Response response = client.newCall(request).execute(); assertSame(interceptorResponse, response); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Ignore @Test/*from w w w.j av a 2 s . com*/ public void networkInterceptorsCannotShortCircuitResponses() throws Exception { server.enqueue(new MockResponse().setResponseCode(500)); Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return new Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200) .message("Intercepted!") .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "abc")).build(); } }; client.networkInterceptors().add(interceptor); Request request = new Request.Builder().url(server.url("/")).build(); try { client.newCall(request).execute(); fail(); } catch (IllegalStateException expected) { assertEquals("network interceptor " + interceptor + " must call proceed() exactly once", expected.getMessage()); } }
From source file:com.android.mms.service_alt.MmsHttpClient.java
License:Apache License
/** * Open an HTTP connection/*w w w .ja v a 2 s . c o m*/ * * TODO: The following code is borrowed from android.net.Network.openConnection * Once that method supports proxy, we should use that instead * Also we should remove the associated HostResolver and ConnectionPool from * MmsNetworkManager * * @param url The URL to connect to * @param proxy The proxy to use * @return The opened HttpURLConnection * @throws MalformedURLException If URL is malformed */ private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException { final String protocol = url.getProtocol(); OkHttpClient okHttpClient; if (protocol.equals("http")) { okHttpClient = new OkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); okHttpClient.setProxySelector(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (proxy != null) { return Arrays.asList(proxy); } else { return new ArrayList<Proxy>(); } } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { } }); okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT)); okHttpClient.setConnectionPool(new ConnectionPool(3, 60000)); okHttpClient.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(okHttpClient, mHostResolver); if (proxy != null) { okHttpClient.setProxy(proxy); } return new HttpURLConnectionImpl(url, okHttpClient); } else if (protocol.equals("https")) { okHttpClient = new OkHttpClient(); okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); okHttpClient.setHostnameVerifier(verifier); okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory()); okHttpClient.setProxySelector(new ProxySelector() { @Override public List<Proxy> select(URI uri) { return Arrays.asList(proxy); } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { } }); okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT)); okHttpClient.setConnectionPool(new ConnectionPool(3, 60000)); Internal.instance.setNetwork(okHttpClient, mHostResolver); return new HttpsURLConnectionImpl(url, okHttpClient); } else { throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol); } }
From source file:com.cml.rx.android.api.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); }//from w w w . java 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() + ' ' + request.url() + ' ' + protocol; if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.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) { logger.log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { logger.log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); // Skip headers from the request body as they are explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { logger.log(name + ": " + headers.value(i)); } } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { logger.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) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " 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 || !HttpEngine.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { logger.log("<-- END HTTP (encoded body omitted)"); } 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) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logger.log(""); logger.log("Couldn't decode the response body; charset is likely malformed."); logger.log("<-- END HTTP"); return response; } } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } return response; }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java
License:Apache License
@Test public void testFetchNotFound() throws Exception { final List<Response> responseList = Lists.newArrayList(); HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"), /* doStore */ true, new FakeProjectFilesystem(), BUCK_EVENT_BUS) { @Override/*from w w w.j a va2 s . co m*/ protected Response fetchCall(Request request) throws IOException { Response response = new Response.Builder().code(HttpURLConnection.HTTP_NOT_FOUND) .body(ResponseBody.create(MediaType.parse("application/octet-stream"), "extraneous")) .protocol(Protocol.HTTP_1_1).request(request).build(); responseList.add(response); return response; } }; CacheResult result = cache.fetch(new RuleKey("00000000000000000000000000000000"), Paths.get("output/file")); assertEquals(result.getType(), CacheResultType.MISS); assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted()); cache.close(); }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java
License:Apache License
@Test public void testFetchOK() throws Exception { Path output = Paths.get("output/file"); final String data = "test"; final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000"); FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); final List<Response> responseList = Lists.newArrayList(); HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"), /* doStore */ true, filesystem, BUCK_EVENT_BUS) { @Override//from w w w.j a va 2s.c o m protected Response fetchCall(Request request) throws IOException { Response response = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1) .code(HttpURLConnection.HTTP_OK) .body(createResponseBody(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), ByteSource.wrap(data.getBytes(Charsets.UTF_8)), data)) .build(); responseList.add(response); return response; } }; CacheResult result = cache.fetch(ruleKey, output); assertEquals(result.cacheError().or(""), CacheResultType.HIT, result.getType()); assertEquals(Optional.of(data), filesystem.readFileIfItExists(output)); assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted()); cache.close(); }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java
License:Apache License
@Test public void testFetchUrl() throws Exception { final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000"); final String expectedUri = "http://localhost:8080/artifacts/key/00000000000000000000000000000000"; HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"), /* doStore */ true, new FakeProjectFilesystem(), BUCK_EVENT_BUS) { @Override// www . j a v a2 s. co m protected Response fetchCall(Request request) throws IOException { assertEquals(expectedUri, request.uri().toString()); return new Response.Builder().request(request).protocol(Protocol.HTTP_1_1) .code(HttpURLConnection.HTTP_OK).body(createResponseBody(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), ByteSource.wrap(new byte[0]), "data")) .build(); } }; cache.fetch(ruleKey, Paths.get("output/file")); cache.close(); }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java
License:Apache License
@Test public void testFetchBadChecksum() throws Exception { FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000"); final List<Response> responseList = Lists.newArrayList(); HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"), /* doStore */ true, filesystem, BUCK_EVENT_BUS) { @Override//from w ww .j a va2s .c o m protected Response fetchCall(Request request) throws IOException { Response response = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1) .code(HttpURLConnection.HTTP_OK).body(createResponseBody(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), ByteSource.wrap(new byte[0]), "data")) .build(); responseList.add(response); return response; } }; Path output = Paths.get("output/file"); CacheResult result = cache.fetch(ruleKey, output); assertEquals(CacheResultType.ERROR, result.getType()); assertEquals(Optional.<String>absent(), filesystem.readFileIfItExists(output)); assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted()); cache.close(); }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java
License:Apache License
@Test public void testFetchExtraPayload() throws Exception { FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000"); final List<Response> responseList = Lists.newArrayList(); HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"), /* doStore */ true, filesystem, BUCK_EVENT_BUS) { @Override//from w w w . j ava2s . co m protected Response fetchCall(Request request) throws IOException { Response response = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1) .code(HttpURLConnection.HTTP_OK) .body(createResponseBody(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), ByteSource.wrap("more data than length".getBytes(Charsets.UTF_8)), "small")) .build(); responseList.add(response); return response; } }; Path output = Paths.get("output/file"); CacheResult result = cache.fetch(ruleKey, output); assertEquals(CacheResultType.ERROR, result.getType()); assertEquals(Optional.<String>absent(), filesystem.readFileIfItExists(output)); assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted()); cache.close(); }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java
License:Apache License
@Test public void testStore() throws Exception { final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000"); final String data = "data"; FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); Path output = Paths.get("output/file"); filesystem.writeContentsToPath(data, output); final AtomicBoolean hasCalled = new AtomicBoolean(false); HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"), /* doStore */ true, filesystem, BUCK_EVENT_BUS) { @Override/*from w w w . j a v a2 s .com*/ protected Response storeCall(Request request) throws IOException { hasCalled.set(true); Buffer buf = new Buffer(); request.body().writeTo(buf); byte[] actualData = buf.readByteArray(); byte[] expectedData; try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out)) { dataOut.write(HttpArtifactCacheBinaryProtocol.createKeysHeader(ImmutableSet.of(ruleKey))); byte[] metadata = HttpArtifactCacheBinaryProtocol.createMetadataHeader(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), ByteSource.wrap(data.getBytes(Charsets.UTF_8))); dataOut.writeInt(metadata.length); dataOut.write(metadata); dataOut.write(data.getBytes(Charsets.UTF_8)); expectedData = out.toByteArray(); } assertArrayEquals(expectedData, actualData); return new Response.Builder().code(HttpURLConnection.HTTP_ACCEPTED).protocol(Protocol.HTTP_1_1) .request(request).build(); } }; cache.storeImpl(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), output, createFinishedEventBuilder()); assertTrue(hasCalled.get()); cache.close(); }