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:alberto.avengers.model.rest.utils.interceptors.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 .j av a 2s. c om*/ 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)); } String endMessage = "--> END " + request.method(); 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)); 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)); } String endMessage = "<-- END HTTP"; if (logBody) { 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 (responseBody.contentLength() != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } endMessage += " (" + buffer.size() + "-byte body)"; } logger.log(endMessage); } return response; }
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
private void parseMultiStatus_Response(XmlPullParser parser) throws IOException, XmlPullParserException, HttpException, UnsupportedDavException { /* <!ELEMENT response (href, ((href*, status)|(propstat+)), error?, responsedescription? , location?) > */ final int depth = parser.getDepth(); HttpUrl href = null;/*from w w w . j ava2s. c o m*/ StatusLine status = null; PropertyCollection properties = new PropertyCollection(); int eventType = parser.getEventType(); while (!(eventType == XmlPullParser.END_TAG && parser.getDepth() == depth)) { if (eventType == XmlPullParser.START_TAG && parser.getDepth() == depth + 1) { String ns = parser.getNamespace(), name = parser.getName(); if (XmlUtils.NS_WEBDAV.equals(ns)) switch (name) { case "href": String sHref = parser.nextText(); if (!sHref.startsWith("/")) { /* According to RFC 4918 8.3 URL Handling, only absolute paths are allowed as relative URLs. However, some servers reply with relative paths. */ int firstColon = sHref.indexOf(':'); if (firstColon != -1) { /* There are some servers which return not only relative paths, but relative paths like "a:b.vcf", which would be interpreted as scheme: "a", scheme-specific part: "b.vcf" normally. For maximum compatibility, we prefix all relative paths which contain ":" (but not "://"), with "./" to allow resolving by HttpUrl. */ boolean hierarchical = false; try { if ("://".equals(sHref.substring(firstColon, firstColon + 3))) hierarchical = true; } catch (IndexOutOfBoundsException e) { // no "://" } if (!hierarchical) sHref = "./" + sHref; } } href = location.resolve(sHref); break; case "status": try { status = StatusLine.parse(parser.nextText()); } catch (ProtocolException e) { log.warn("Invalid status line, treating as 500 Server Error"); status = new StatusLine(Protocol.HTTP_1_1, 500, "Invalid status line"); } break; case "propstat": PropertyCollection prop = parseMultiStatus_PropStat(parser); if (prop != null) properties.merge(prop, false); break; case "location": throw new UnsupportedDavException("Redirected child resources are not supported yet"); } } eventType = parser.next(); } if (href == null) { log.warn("Ignoring <response> without valid <href>"); return; } // if we know this resource is a collection, make sure href has a trailing slash (for clarity and resolving relative paths) ResourceType type = (ResourceType) properties.get(ResourceType.NAME); if (type != null && type.types.contains(ResourceType.COLLECTION)) href = UrlUtils.withTrailingSlash(href); log.debug("Received <response> for " + href + ", status: " + status + ", properties: " + properties); if (status != null) // treat an HTTP error of a single response (i.e. requested resource or a member) like an HTTP error of the requested resource checkStatus(status); // Which resource does this <response> represent? DavResource target = null; if (UrlUtils.equals(UrlUtils.omitTrailingSlash(href), UrlUtils.omitTrailingSlash(location))) { // it's about ourselves target = this; } else if (location.scheme().equals(href.scheme()) && location.host().equals(href.host()) && location.port() == href.port()) { List<String> locationSegments = location.pathSegments(), hrefSegments = href.pathSegments(); // don't compare trailing slash segment ("") int nBasePathSegments = locationSegments.size(); if ("".equals(locationSegments.get(nBasePathSegments - 1))) nBasePathSegments--; /* example: locationSegments = [ "davCollection", "" ] nBasePathSegments = 1 hrefSegments = [ "davCollection", "aMember" ] */ if (hrefSegments.size() > nBasePathSegments) { boolean sameBasePath = true; for (int i = 0; i < nBasePathSegments; i++) { if (!locationSegments.get(i).equals(hrefSegments.get(i))) { sameBasePath = false; break; } } if (sameBasePath) members.add(target = new DavResource(log, httpClient, href)); } } // set properties for target if (target != null) target.properties.merge(properties, true); else log.warn("Received <response> not for self and not for member resource"); }
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
private PropertyCollection parseMultiStatus_PropStat(XmlPullParser parser) throws IOException, XmlPullParserException { // <!ELEMENT propstat (prop, status, error?, responsedescription?) > final int depth = parser.getDepth(); StatusLine status = null;//from w w w . j a v a 2 s . co m PropertyCollection prop = null; int eventType = parser.getEventType(); while (!(eventType == XmlPullParser.END_TAG && parser.getDepth() == depth)) { if (eventType == XmlPullParser.START_TAG && parser.getDepth() == depth + 1) { String ns = parser.getNamespace(), name = parser.getName(); if (XmlUtils.NS_WEBDAV.equals(ns)) switch (name) { case "prop": prop = parseMultiStatus_Prop(parser); break; case "status": try { status = StatusLine.parse(parser.nextText()); } catch (ProtocolException e) { log.warn("Invalid status line, treating as 500 Server Error"); status = new StatusLine(Protocol.HTTP_1_1, 500, "Invalid status line"); } } } eventType = parser.next(); } if (status != null && status.code / 100 != 2) // not successful, null out property values so that they can be removed when merging in parseMultiStatus_Response prop.nullAllValues(); return prop; }
From source file:at.bitfire.dav4android.exception.ServiceUnavailableExceptionTest.java
License:Open Source License
public void testRetryAfter() { Response response = new Response.Builder() .request(new Request.Builder().url("http://www.example.com").get().build()) .protocol(Protocol.HTTP_1_1).code(503).build(); ServiceUnavailableException e = new ServiceUnavailableException(response); assertNull(e.retryAfter);// w ww. j a v a 2 s . co m response = response.newBuilder().header("Retry-After", "120").build(); e = new ServiceUnavailableException(response); assertNotNull(e.retryAfter); assertTrue(withinTimeRange(e.retryAfter, 120)); Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, 30); response = response.newBuilder().header("Retry-After", HttpDate.format(cal.getTime())).build(); e = new ServiceUnavailableException(response); assertNotNull(e.retryAfter); assertTrue(withinTimeRange(e.retryAfter, 30 * 60)); }
From source file:client.lib.Client.java
public Client() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { X509Certificate[] myTrustedAnchors = new X509Certificate[0]; return myTrustedAnchors; }/* w ww. ja va 2 s .c om*/ @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); http2Client = new OkHttpClient(); http2Client.setSslSocketFactory(sslSocketFactory); http2Client.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); httpClient = http2Client.clone(); httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2)); }
From source file:client.ui.Container.java
private void initClients() { http2Client = new OkHttpClient(); httpClient = http2Client.clone();// www . ja v a 2s . co m httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2)); }
From source file:cn.com.canon.darwin.modules.service.api.interceptor.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. j a va 2s .c om 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:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
/** * Tests that use this will fail unless boot classpath is set. Ex. {@code * -Xbootclasspath/p:/tmp/alpn-boot-8.0.0.v20140317} *//*from w w w . j a v a2s.c om*/ private void enableProtocol(Protocol protocol) { client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(new RecordingHostnameVerifier()); client.setProtocols(Arrays.asList(protocol, Protocol.HTTP_1_1)); server.get().useHttps(sslContext.getSocketFactory(), false); server.get().setProtocols(client.getProtocols()); }
From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java
License:Open Source License
@Test public void applicationInterceptorsCanShortCircuitResponses() throws Exception { server.get().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/*from ww w.j a v a 2 s . c o m*/ public Response intercept(Chain chain) throws IOException { return interceptorResponse; } }); Response response = FiberOkHttpUtil.executeInFiber(client, request); assertSame(interceptorResponse, response); }
From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java
License:Open Source License
@Ignore @Test/*from w ww . j a v a2 s. co m*/ 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.getUrl("/")).build(); try { FiberOkHttpUtil.executeInFiber(client, request); fail(); } catch (IllegalStateException expected) { assertEquals("network interceptor " + interceptor + " must call proceed() exactly once", expected.getMessage()); } }