use of okhttp3.Protocol in project okhttp by square.
the class ResponseCacheTest method secureResponseCachingAndProtocolRedirects.
/**
* We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal
* to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and
* HttpURLConnection was always HTTP; in practice redirects mean that each can do either.
*
* https://github.com/square/okhttp/issues/214
*/
@Test
public void secureResponseCachingAndProtocolRedirects() throws IOException {
server2.useHttps(sslClient.socketFactory, false);
server2.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setBody("ABC"));
server2.enqueue(new MockResponse().setBody("DEF"));
server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(HttpURLConnection.HTTP_MOVED_PERM).addHeader("Location: " + server2.url("/").url()));
urlFactory.setClient(urlFactory.client().newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build());
HttpURLConnection connection1 = openConnection(server.url("/").url());
assertEquals("ABC", readAscii(connection1));
// Cached!
HttpURLConnection connection2 = openConnection(server.url("/").url());
assertEquals("ABC", readAscii(connection2));
}
use of okhttp3.Protocol in project okhttp by square.
the class HttpLoggingInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
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.protocol() : 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) {
// 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 || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
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;
}
use of okhttp3.Protocol in project okhttp by square.
the class CallTest method interceptorGetsHttp2.
@Test
public void interceptorGetsHttp2() throws Exception {
enableProtocol(Protocol.HTTP_2);
// Capture the protocol as it is observed by the interceptor.
final AtomicReference<Protocol> protocolRef = new AtomicReference<>();
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
protocolRef.set(chain.connection().protocol());
return chain.proceed(chain.request());
}
};
client = client.newBuilder().addNetworkInterceptor(interceptor).build();
// Make an HTTP/2 request and confirm that the protocol matches.
server.enqueue(new MockResponse());
executeSynchronously("/");
assertEquals(Protocol.HTTP_2, protocolRef.get());
}
use of okhttp3.Protocol in project okhttp by square.
the class InterceptorTest method applicationInterceptorsCanShortCircuitResponses.
@Test
public void applicationInterceptorsCanShortCircuitResponses() throws Exception {
// Accept no connections.
server.shutdown();
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 = client.newBuilder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
return interceptorResponse;
}
}).build();
Response response = client.newCall(request).execute();
assertSame(interceptorResponse, response);
}
use of okhttp3.Protocol in project okhttp by square.
the class ExternalHttp2Example method main.
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient.Builder().protocols(Util.immutableList(Protocol.HTTP_2, Protocol.HTTP_1_1)).build();
Call call = client.newCall(new Request.Builder().url("https://www.google.ca/").build());
Response response = call.execute();
try {
System.out.println(response.code());
System.out.println("PROTOCOL " + response.protocol());
String line;
while ((line = response.body().source().readUtf8Line()) != null) {
System.out.println(line);
}
} finally {
response.body().close();
}
client.connectionPool().evictAll();
}
Aggregations