use of okhttp3.Protocol in project okhttp by square.
the class RealConnection method connectTls.
private void connectTls(ConnectionSpecSelector connectionSpecSelector) throws IOException {
Address address = route.address();
SSLSocketFactory sslSocketFactory = address.sslSocketFactory();
boolean success = false;
SSLSocket sslSocket = null;
try {
// Create the wrapper over the connected socket.
sslSocket = (SSLSocket) sslSocketFactory.createSocket(rawSocket, address.url().host(), address.url().port(), true);
// Configure the socket's ciphers, TLS versions, and extensions.
ConnectionSpec connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket);
if (connectionSpec.supportsTlsExtensions()) {
Platform.get().configureTlsExtensions(sslSocket, address.url().host(), address.protocols());
}
// Force handshake. This can throw!
sslSocket.startHandshake();
Handshake unverifiedHandshake = Handshake.get(sslSocket.getSession());
// Verify that the socket's certificates are acceptable for the target host.
if (!address.hostnameVerifier().verify(address.url().host(), sslSocket.getSession())) {
X509Certificate cert = (X509Certificate) unverifiedHandshake.peerCertificates().get(0);
throw new SSLPeerUnverifiedException("Hostname " + address.url().host() + " not verified:" + "\n certificate: " + CertificatePinner.pin(cert) + "\n DN: " + cert.getSubjectDN().getName() + "\n subjectAltNames: " + OkHostnameVerifier.allSubjectAltNames(cert));
}
// Check that the certificate pinner is satisfied by the certificates presented.
address.certificatePinner().check(address.url().host(), unverifiedHandshake.peerCertificates());
// Success! Save the handshake and the ALPN protocol.
String maybeProtocol = connectionSpec.supportsTlsExtensions() ? Platform.get().getSelectedProtocol(sslSocket) : null;
socket = sslSocket;
source = Okio.buffer(Okio.source(socket));
sink = Okio.buffer(Okio.sink(socket));
handshake = unverifiedHandshake;
protocol = maybeProtocol != null ? Protocol.get(maybeProtocol) : Protocol.HTTP_1_1;
success = true;
} catch (AssertionError e) {
if (Util.isAndroidGetsocknameError(e))
throw new IOException(e);
throw e;
} finally {
if (sslSocket != null) {
Platform.get().afterHandshake(sslSocket);
}
if (!success) {
closeQuietly(sslSocket);
}
}
}
use of okhttp3.Protocol in project okhttp by square.
the class Platform method alpnProtocolNames.
public static List<String> alpnProtocolNames(List<Protocol> protocols) {
List<String> names = new ArrayList<>(protocols.size());
for (int i = 0, size = protocols.size(); i < size; i++) {
Protocol protocol = protocols.get(i);
// No HTTP/1.0 for ALPN.
if (protocol == Protocol.HTTP_1_0)
continue;
names.add(protocol.toString());
}
return names;
}
use of okhttp3.Protocol in project okhttp by square.
the class Http2Server method run.
private void run() throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
serverSocket.setReuseAddress(true);
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
SSLSocket sslSocket = doSsl(socket);
String protocolString = Platform.get().getSelectedProtocol(sslSocket);
Protocol protocol = protocolString != null ? Protocol.get(protocolString) : null;
if (protocol != Protocol.HTTP_2) {
throw new ProtocolException("Protocol " + protocol + " unsupported");
}
Http2Connection connection = new Http2Connection.Builder(false).socket(sslSocket).listener(this).build();
connection.start();
} catch (IOException e) {
logger.log(Level.INFO, "Http2Server connection failure: " + e);
Util.closeQuietly(socket);
} catch (Exception e) {
logger.log(Level.WARNING, "Http2Server unexpected failure", e);
Util.closeQuietly(socket);
}
}
}
use of okhttp3.Protocol in project okhttp by square.
the class MockWebServer method handleWebSocketUpgrade.
private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink, RecordedRequest request, MockResponse response) throws IOException {
String key = request.getHeader("Sec-WebSocket-Key");
response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key));
writeHttpResponse(socket, sink, response);
// Adapt the request and response into our Request and Response domain model.
String scheme = request.getTlsVersion() != null ? "https" : "http";
// Has host and port.
String authority = request.getHeader("Host");
final Request fancyRequest = new Request.Builder().url(scheme + "://" + authority + "/").headers(request.getHeaders()).build();
final Response fancyResponse = new Response.Builder().code(Integer.parseInt(response.getStatus().split(" ")[1])).message(response.getStatus().split(" ", 3)[2]).headers(response.getHeaders()).request(fancyRequest).protocol(Protocol.HTTP_1_1).build();
final CountDownLatch connectionClose = new CountDownLatch(1);
RealWebSocket.Streams streams = new RealWebSocket.Streams(false, source, sink) {
@Override
public void close() {
connectionClose.countDown();
}
};
RealWebSocket webSocket = new RealWebSocket(fancyRequest, response.getWebSocketListener(), new SecureRandom());
response.getWebSocketListener().onOpen(webSocket, fancyResponse);
String name = "MockWebServer WebSocket " + request.getPath();
webSocket.initReaderAndWriter(name, 0, streams);
try {
webSocket.loopReader();
// Even if messages are no longer being read we need to wait for the connection close signal.
try {
connectionClose.await();
} catch (InterruptedException ignored) {
}
} catch (IOException e) {
webSocket.failWebSocket(e, null);
} finally {
closeQuietly(sink);
closeQuietly(source);
}
}
use of okhttp3.Protocol in project okhttp by square.
the class JavaApiConverterTest method createJavaUrlConnection_responseHeadersOk.
@Test
public void createJavaUrlConnection_responseHeadersOk() throws Exception {
ResponseBody responseBody = createResponseBody("BodyText");
Response okResponse = new Response.Builder().request(createArbitraryOkRequest()).protocol(Protocol.HTTP_1_1).code(200).message("Fantastic").addHeader("A", "c").addHeader("B", "d").addHeader("A", "e").addHeader("Content-Length", Long.toString(responseBody.contentLength())).body(responseBody).build();
HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnectionForCachePut(okResponse);
assertEquals(200, httpUrlConnection.getResponseCode());
assertEquals("Fantastic", httpUrlConnection.getResponseMessage());
assertEquals(responseBody.contentLength(), httpUrlConnection.getContentLength());
// Check retrieval by string key.
assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(null));
assertEquals("e", httpUrlConnection.getHeaderField("A"));
// The RI and OkHttp supports case-insensitive matching for this method.
assertEquals("e", httpUrlConnection.getHeaderField("a"));
// Check retrieval using a Map.
Map<String, List<String>> responseHeaders = httpUrlConnection.getHeaderFields();
assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), responseHeaders.get(null));
assertEquals(newSet("c", "e"), newSet(responseHeaders.get("A")));
// OkHttp supports case-insensitive matching here. The RI does not.
assertEquals(newSet("c", "e"), newSet(responseHeaders.get("a")));
// Check the Map iterator contains the expected mappings.
assertHeadersContainsMapping(responseHeaders, null, "HTTP/1.1 200 Fantastic");
assertHeadersContainsMapping(responseHeaders, "A", "c", "e");
assertHeadersContainsMapping(responseHeaders, "B", "d");
// Check immutability of the headers Map.
try {
responseHeaders.put("N", Arrays.asList("o"));
fail("Modified an unmodifiable view.");
} catch (UnsupportedOperationException expected) {
}
try {
responseHeaders.get("A").add("f");
fail("Modified an unmodifiable view.");
} catch (UnsupportedOperationException expected) {
}
// Check retrieval of headers by index.
assertEquals(null, httpUrlConnection.getHeaderFieldKey(0));
assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(0));
// After header zero there may be additional entries provided at the beginning or end by the
// implementation. It's probably important that the relative ordering of the headers is
// preserved, particularly if there are multiple value for the same key.
int i = 1;
while (!httpUrlConnection.getHeaderFieldKey(i).equals("A")) {
i++;
}
// Check the ordering of the headers set by app code.
assertResponseHeaderAtIndex(httpUrlConnection, i++, "A", "c");
assertResponseHeaderAtIndex(httpUrlConnection, i++, "B", "d");
assertResponseHeaderAtIndex(httpUrlConnection, i++, "A", "e");
// There may be some additional headers provided by the implementation.
while (httpUrlConnection.getHeaderField(i) != null) {
assertNotNull(httpUrlConnection.getHeaderFieldKey(i));
i++;
}
// Confirm the correct behavior when the index is out-of-range.
assertNull(httpUrlConnection.getHeaderFieldKey(i));
}
Aggregations