@Test public void shouldSendGetRequest() throws ExecutionException, InterruptedException { final Request request = new com.squareup.okhttp.Request.Builder() .url(URI) .method("GET", null) .build(); when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call); doAnswer(invocation -> { final Callback callback = invocation.getArgument(0); callback.onResponse(new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(Status.OK.code()) .message("OK") .body(ResponseBody.create(CONTENT_TYPE, "{}")) .header("foo", "bar") .build()); return Void.TYPE; }).when(call).enqueue(isA(Callback.class)); final com.spotify.apollo.Response<ByteString> response = client.send(com.spotify.apollo.Request.forUri(URI, "GET")).toCompletableFuture().get(); verify(okHttpClient, never()).setReadTimeout(anyLong(), any()); assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload()); assertEquals(Optional.of("bar"), response.header("foo")); }
public void writeRequestHeaders(Request request) throws IOException { if (this.stream == null) { List<Header> requestHeaders; this.httpEngine.writingRequestHeaders(); boolean permitsRequestBody = this.httpEngine.permitsRequestBody(request); if (this.framedConnection.getProtocol() == Protocol.HTTP_2) { requestHeaders = http2HeadersList(request); } else { requestHeaders = spdy3HeadersList(request); } this.stream = this.framedConnection.newStream(requestHeaders, permitsRequestBody, true); this.stream.readTimeout().timeout((long) this.httpEngine.client.getReadTimeout(), TimeUnit.MILLISECONDS); this.stream.writeTimeout().timeout((long) this.httpEngine.client.getWriteTimeout(), TimeUnit.MILLISECONDS); } }
public static Response$Builder readHttp2HeadersList(List<Header> headerBlock) throws IOException { String status = null; Builder headersBuilder = new Builder(); int size = headerBlock.size(); for (int i = 0; i < size; i++) { ByteString name = ((Header) headerBlock.get(i)).name; String value = ((Header) headerBlock.get(i)).value.utf8(); if (name.equals(Header.RESPONSE_STATUS)) { status = value; } else if (!HTTP_2_SKIPPED_RESPONSE_HEADERS.contains(name)) { headersBuilder.add(name.utf8(), value); } } if (status == null) { throw new ProtocolException("Expected ':status' header not present"); } StatusLine statusLine = StatusLine.parse("HTTP/1.1 " + status); return new Response$Builder().protocol(Protocol.HTTP_2).code(statusLine.code).message (statusLine.message).headers(headersBuilder.build()); }
private void setProtocols(String protocolsString, boolean append) { List<Protocol> protocolsList = new ArrayList(); if (append) { protocolsList.addAll(this.client.getProtocols()); } String[] split = protocolsString.split(",", -1); int length = split.length; int i = 0; while (i < length) { try { protocolsList.add(Protocol.get(split[i])); i++; } catch (IOException e) { throw new IllegalStateException(e); } } this.client.setProtocols(protocolsList); }
private void connectSocket(int connectTimeout, int readTimeout, int writeTimeout, ConnectionSpecSelector connectionSpecSelector) throws IOException { this.rawSocket.setSoTimeout(readTimeout); try { Platform.get().connectSocket(this.rawSocket, this.route.getSocketAddress(), connectTimeout); this.source = Okio.buffer(Okio.source(this.rawSocket)); this.sink = Okio.buffer(Okio.sink(this.rawSocket)); if (this.route.getAddress().getSslSocketFactory() != null) { connectTls(readTimeout, writeTimeout, connectionSpecSelector); } else { this.protocol = Protocol.HTTP_1_1; this.socket = this.rawSocket; } if (this.protocol == Protocol.SPDY_3 || this.protocol == Protocol.HTTP_2) { this.socket.setSoTimeout(0); FramedConnection framedConnection = new Builder(true).socket(this.socket, this .route.getAddress().url().host(), this.source, this.sink).protocol(this .protocol).build(); framedConnection.sendConnectionPreface(); this.framedConnection = framedConnection; } } catch (ConnectException e) { throw new ConnectException("Failed to connect to " + this.route.getSocketAddress()); } }
private static ProtocolVersion parseProtocol(final Protocol p) { switch (p) { case HTTP_1_0: return new ProtocolVersion("HTTP", 1, 0); case HTTP_1_1: return new ProtocolVersion("HTTP", 1, 1); case SPDY_3: return new ProtocolVersion("SPDY", 3, 1); case HTTP_2: return new ProtocolVersion("HTTP", 2, 0); } throw new IllegalAccessError("Unkwown protocol"); }
private static ProtocolVersion parseProtocol(final Protocol protocol) { switch (protocol) { case HTTP_1_0: return new ProtocolVersion("HTTP", 1, 0); case HTTP_1_1: return new ProtocolVersion("HTTP", 1, 1); case SPDY_3: return new ProtocolVersion("SPDY", 3, 1); case HTTP_2: return new ProtocolVersion("HTTP", 2, 0); } throw new IllegalAccessError("Unkwown protocol"); }
/** * Initializes the global URLStreamHandlerFactory. * <p> * This method is invoked by {@link #init(boolean, boolean)}. */ public static void initProtocols(final SSLSocketFactory sslSocketFactory) { // Configure URL protocol handlers final PlatformStreamHandlerFactory factory = PlatformStreamHandlerFactory.getInstance(); URL.setURLStreamHandlerFactory(factory); final OkHttpClient okHttpClient = new OkHttpClient(); final ArrayList<Protocol> protocolList = new ArrayList<>(2); protocolList.add(Protocol.HTTP_1_1); protocolList.add(Protocol.HTTP_2); okHttpClient.setProtocols(protocolList); okHttpClient.setConnectTimeout(100, TimeUnit.SECONDS); // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); factory.addFactory(new OkUrlFactory(okHttpClient)); factory.addFactory(new LocalStreamHandlerFactory()); }
/** * Returns the request status line, like "GET / HTTP/1.1". This is exposed * to the application by {@link HttpURLConnection#getHeaderFields}, so it * needs to be set even if the transport is SPDY. */ static String get(Request request, Proxy.Type proxyType, Protocol protocol) { StringBuilder result = new StringBuilder(); result.append(request.method()); result.append(' '); if (includeAuthorityInRequestLine(request, proxyType)) { result.append(request.url()); } else { result.append(requestPath(request.url())); } result.append(' '); result.append(version(protocol)); return result.toString(); }
/** Parses bytes of a response header from an HTTP transport. */ public Response.Builder readResponse() throws IOException { if (state != STATE_OPEN_REQUEST_BODY && state != STATE_READ_RESPONSE_HEADERS) { throw new IllegalStateException("state: " + state); } while (true) { String statusLineString = source.readUtf8LineStrict(); StatusLine statusLine = new StatusLine(statusLineString); Response.Builder responseBuilder = new Response.Builder() .statusLine(statusLine) .header(OkHeaders.SELECTED_PROTOCOL, Protocol.HTTP_11.name.utf8()); Headers.Builder headersBuilder = new Headers.Builder(); readHeaders(headersBuilder); responseBuilder.headers(headersBuilder.build()); if (statusLine.code() != HTTP_CONTINUE) { state = STATE_OPEN_RESPONSE_BODY; return responseBuilder; } } }
@Test public void parseNameValueBlock() throws IOException { List<Header> headerBlock = headerEntries( "cache-control", "no-cache, no-store", "set-cookie", "Cookie1\u0000Cookie2", ":status", "200 OK", ":version", "HTTP/1.1"); Request request = new Request.Builder().url("http://square.com/").build(); Response response = SpdyTransport.readNameValueBlock(headerBlock, Protocol.SPDY_3).request(request).build(); Headers headers = response.headers(); assertEquals(4, headers.size()); assertEquals("HTTP/1.1 200 OK", response.statusLine()); assertEquals("no-cache, no-store", headers.get("cache-control")); assertEquals("Cookie2", headers.get("set-cookie")); assertEquals(Protocol.SPDY_3.name.utf8(), headers.get(OkHeaders.SELECTED_PROTOCOL)); assertEquals(OkHeaders.SELECTED_PROTOCOL, headers.name(0)); assertEquals(Protocol.SPDY_3.name.utf8(), headers.value(0)); assertEquals("cache-control", headers.name(1)); assertEquals("no-cache, no-store", headers.value(1)); assertEquals("set-cookie", headers.name(2)); assertEquals("Cookie1", headers.value(2)); assertEquals("set-cookie", headers.name(3)); assertEquals("Cookie2", headers.value(3)); assertNull(headers.get(":status")); assertNull(headers.get(":version")); }
@Test public void toNameValueBlock() { Request request = new Request.Builder() .url("http://square.com/") .header("cache-control", "no-cache, no-store") .addHeader("set-cookie", "Cookie1") .addHeader("set-cookie", "Cookie2") .header(":status", "200 OK") .build(); List<Header> headerBlock = SpdyTransport.writeNameValueBlock(request, Protocol.SPDY_3, "HTTP/1.1"); List<Header> expected = headerEntries( ":method", "GET", ":path", "/", ":version", "HTTP/1.1", ":host", "square.com", ":scheme", "http", "cache-control", "no-cache, no-store", "set-cookie", "Cookie1\u0000Cookie2", ":status", "200 OK"); assertEquals(expected, headerBlock); }
private Socket doSsl(Socket socket) throws IOException { SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(false); NextProtoNego.put(sslSocket, new NextProtoNego.ServerProvider() { @Override public void unsupported() { System.out.println("UNSUPPORTED"); } @Override public List<String> protocols() { return Arrays.asList(Protocol.SPDY_3.name.utf8()); } @Override public void protocolSelected(String protocol) { System.out.println("PROTOCOL SELECTED: " + protocol); } }); return sslSocket; }
private void pushPromises(SpdyStream stream, List<PushPromise> promises) throws IOException { for (PushPromise pushPromise : promises) { List<Header> pushedHeaders = new ArrayList<Header>(); pushedHeaders.add(new Header(stream.getConnection().getProtocol() == Protocol.SPDY_3 ? Header.TARGET_HOST : Header.TARGET_AUTHORITY, getUrl(pushPromise.getPath()).getHost())); pushedHeaders.add(new Header(Header.TARGET_METHOD, pushPromise.getMethod())); pushedHeaders.add(new Header(Header.TARGET_PATH, pushPromise.getPath())); for (int i = 0, size = pushPromise.getHeaders().size(); i < size; i++) { String header = pushPromise.getHeaders().get(i); String[] headerParts = header.split(":", 2); if (headerParts.length != 2) { throw new AssertionError("Unexpected header: " + header); } pushedHeaders.add(new Header(headerParts[0], headerParts[1].trim())); } String requestLine = pushPromise.getMethod() + ' ' + pushPromise.getPath() + " HTTP/1.1"; List<Integer> chunkSizes = Collections.emptyList(); // No chunked encoding for SPDY. requestQueue.add(new RecordedRequest(requestLine, pushPromise.getHeaders(), chunkSizes, 0, Util.EMPTY_BYTE_ARRAY, sequenceNumber.getAndIncrement(), socket)); byte[] pushedBody = pushPromise.getResponse().getBody(); SpdyStream pushedStream = stream.getConnection().pushStream(stream.getId(), pushedHeaders, pushedBody.length > 0); writeResponse(pushedStream, pushPromise.getResponse()); } }
@Inject public TwitterClient() { if(restAdapter == null || iTwitterClient == null) { OkHttpClient client = new OkHttpClient(); client.setProtocols(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2, Protocol.SPDY_3)); restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint(API_URL) .setClient(new OkClient(client)) .build(); iTwitterClient = restAdapter.create(ITwitterClient.class); } }
/** * @return a new http client */ 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; }
/** * Constructor. * @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); }
@Test public void shouldSendPostRequest() throws ExecutionException, InterruptedException { final Request request = new com.squareup.okhttp.Request.Builder() .url(URI) .method("POST", RequestBody.create(CONTENT_TYPE, "{}")) .build(); when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call); doAnswer(invocation -> { final Callback callback = invocation.getArgument(0); callback.onResponse(new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(Status.OK.code()) .message("OK") .body(ResponseBody.create(CONTENT_TYPE, "{}")) .header("foo", "bar") .build()); return Void.TYPE; }).when(call).enqueue(isA(Callback.class)); final com.spotify.apollo.Response<ByteString> response = client.send(com.spotify.apollo.Request .forUri(URI, "POST") .withPayload(ByteString.of("{}".getBytes()))) .toCompletableFuture().get(); verify(okHttpClient, never()).setReadTimeout(anyLong(), any()); assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload()); assertEquals(Optional.of("bar"), response.header("foo")); }
public static StatusLine parse(String statusLine) throws IOException { int codeStart; Protocol protocol; if (statusLine.startsWith("HTTP/1.")) { if (statusLine.length() < 9 || statusLine.charAt(8) != ' ') { throw new ProtocolException("Unexpected status line: " + statusLine); } int httpMinorVersion = statusLine.charAt(7) - 48; codeStart = 9; if (httpMinorVersion == 0) { protocol = Protocol.HTTP_1_0; } else if (httpMinorVersion == 1) { protocol = Protocol.HTTP_1_1; } else { throw new ProtocolException("Unexpected status line: " + statusLine); } } else if (statusLine.startsWith("ICY ")) { protocol = Protocol.HTTP_1_0; codeStart = 4; } else { throw new ProtocolException("Unexpected status line: " + statusLine); } if (statusLine.length() < codeStart + 3) { throw new ProtocolException("Unexpected status line: " + statusLine); } try { int code = Integer.parseInt(statusLine.substring(codeStart, codeStart + 3)); String message = ""; if (statusLine.length() > codeStart + 3) { if (statusLine.charAt(codeStart + 3) != ' ') { throw new ProtocolException("Unexpected status line: " + statusLine); } message = statusLine.substring(codeStart + 4); } return new StatusLine(protocol, code, message); } catch (NumberFormatException e) { throw new ProtocolException("Unexpected status line: " + statusLine); } }
public String toString() { StringBuilder result = new StringBuilder(); result.append(this.protocol == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1"); result.append(' ').append(this.code); if (this.message != null) { result.append(' ').append(this.message); } return result.toString(); }
public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List<Protocol> protocols) { if (hostname != null) { this.setUseSessionTickets.invokeOptionalWithoutCheckedException(sslSocket, Boolean.valueOf(true)); this.setHostname.invokeOptionalWithoutCheckedException(sslSocket, hostname); } if (this.setAlpnProtocols != null && this.setAlpnProtocols.isSupported(sslSocket)) { this.setAlpnProtocols.invokeWithoutCheckedException(sslSocket, Platform .concatLengthPrefixed(protocols)); } }
static byte[] concatLengthPrefixed(List<Protocol> protocols) { Buffer result = new Buffer(); int size = protocols.size(); for (int i = 0; i < size; i++) { Protocol protocol = (Protocol) protocols.get(i); if (protocol != Protocol.HTTP_1_0) { result.writeByte(protocol.toString().length()); result.writeUtf8(protocol.toString()); } } return result.readByteArray(); }
public FramedStream pushStream(int associatedStreamId, List<Header> requestHeaders, boolean out) throws IOException { if (this.client) { throw new IllegalStateException("Client cannot push requests."); } else if (this.protocol == Protocol.HTTP_2) { return newStream(associatedStreamId, requestHeaders, out, false); } else { throw new IllegalStateException("protocol != HTTP_2"); } }
@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); return client; }
public MattermostService(Context context) { this.context = context; String userAgent = context.getResources().getString(R.string.app_user_agent); cookieStore = new WebkitCookieManagerProxy(); client.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); client.setCookieHandler(cookieStore); preferences = context.getSharedPreferences("App", Context.MODE_PRIVATE); }
private Response createJsonResponse(String jsonPayload, int code) { Request request = new Request.Builder() .url("https://someurl.com") .build(); final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), jsonPayload); return new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .body(responseBody) .code(code) .build(); }
private Response createBytesResponse(byte[] content, int code) { Request request = new Request.Builder() .url("https://someurl.com") .build(); final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/octet-stream; charset=utf-8"), content); return new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .body(responseBody) .code(code) .build(); }
public final String toString() { StringBuilder localStringBuilder = new StringBuilder(); if (this.protocol == Protocol.HTTP_1_0) {} for (String str = "HTTP/1.0";; str = "HTTP/1.1") { localStringBuilder.append(str); localStringBuilder.append(' ').append(this.code); if (this.message != null) { localStringBuilder.append(' ').append(this.message); } return localStringBuilder.toString(); } }
public static String version(Protocol paramProtocol) { if (paramProtocol == Protocol.HTTP_1_0) { return "HTTP/1.0"; } return "HTTP/1.1"; }
private static boolean isProhibitedHeader(Protocol paramProtocol, ByteString paramByteString) { if (paramProtocol == Protocol.SPDY_3) { return SPDY_3_PROHIBITED_HEADERS.contains(paramByteString); } if (paramProtocol == Protocol.HTTP_2) { return HTTP_2_PROHIBITED_HEADERS.contains(paramByteString); } throw new AssertionError(paramProtocol); }
public final void writeRequestHeaders(Request paramRequest) throws IOException { this.httpEngine.writingRequestHeaders(); Proxy.Type localType = this.httpEngine.connection.route.proxy.type(); Protocol localProtocol = this.httpEngine.connection.protocol; StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append(paramRequest.method); localStringBuilder.append(' '); int i; if ((!paramRequest.isHttps()) && (localType == Proxy.Type.HTTP)) { i = 1; if (i == 0) { break label139; } localStringBuilder.append(paramRequest.url()); } for (;;) { localStringBuilder.append(' '); localStringBuilder.append(RequestLine.version(localProtocol)); String str = localStringBuilder.toString(); this.httpConnection.writeRequest(paramRequest.headers, str); return; i = 0; break; label139: localStringBuilder.append(RequestLine.requestPath(paramRequest.url())); } }
public final void configureTlsExtensions(SSLSocket paramSSLSocket, String paramString, List<Protocol> paramList) { if (paramString != null) { OptionalMethod localOptionalMethod = SET_USE_SESSION_TICKETS; Object[] arrayOfObject2 = new Object[1]; arrayOfObject2[0] = Boolean.valueOf(true); localOptionalMethod.invokeOptionalWithoutCheckedException(paramSSLSocket, arrayOfObject2); SET_HOSTNAME.invokeOptionalWithoutCheckedException(paramSSLSocket, new Object[] { paramString }); } boolean bool1 = SET_NPN_PROTOCOLS.isSupported(paramSSLSocket); boolean bool2 = SET_ALPN_PROTOCOLS.isSupported(paramSSLSocket); if ((!bool1) && (!bool2)) {} Object[] arrayOfObject1; do { return; arrayOfObject1 = new Object[1]; Buffer localBuffer = new Buffer(); int i = paramList.size(); for (int j = 0; j < i; j++) { Protocol localProtocol = (Protocol)paramList.get(j); if (localProtocol != Protocol.HTTP_1_0) { localBuffer.writeByte(localProtocol.toString().length()); localBuffer.writeUtf8(localProtocol.toString()); } } arrayOfObject1[0] = localBuffer.readByteArray(); if (bool1) { SET_NPN_PROTOCOLS.invokeWithoutCheckedException(paramSSLSocket, arrayOfObject1); } } while (!bool2); SET_ALPN_PROTOCOLS.invokeWithoutCheckedException(paramSSLSocket, arrayOfObject1); }
public final void configureTlsExtensions(SSLSocket paramSSLSocket, String paramString, List<Protocol> paramList) { ArrayList localArrayList = new ArrayList(paramList.size()); int i = 0; int j = paramList.size(); while (i < j) { Protocol localProtocol = (Protocol)paramList.get(i); if (localProtocol != Protocol.HTTP_1_0) { localArrayList.add(localProtocol.toString()); } i++; } try { ClassLoader localClassLoader = Platform.class.getClassLoader(); Class[] arrayOfClass = new Class[2]; arrayOfClass[0] = this.clientProviderClass; arrayOfClass[1] = this.serverProviderClass; Object localObject = Proxy.newProxyInstance(localClassLoader, arrayOfClass, new Platform.JettyNegoProvider(localArrayList)); this.putMethod.invoke(null, new Object[] { paramSSLSocket, localObject }); return; } catch (InvocationTargetException localInvocationTargetException) { throw new AssertionError(localInvocationTargetException); } catch (IllegalAccessException localIllegalAccessException) { throw new AssertionError(localIllegalAccessException); } }