use of okhttp3.JavaNetCookieJar in project keywhiz by square.
the class HttpClients method testSslClient.
/**
* Create a {@link OkHttpClient} for tests.
*
* @param keyStore Use a client certificate from keystore if present. Client certs disabled if null.
* @param keyStorePassword keyStore password. Client certs disabled if null.
* @param requestInterceptors Any request interceptors to register with client.
* @return new http client
*/
private static OkHttpClient testSslClient(@Nullable KeyStore keyStore, @Nullable String keyStorePassword, KeyStore trustStore, List<Interceptor> requestInterceptors) {
boolean usingClientCert = keyStore != null && keyStorePassword != null;
SSLContext sslContext;
try {
SSLContextBuilder sslContextBuilder = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(trustStore);
if (usingClientCert) {
sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray());
}
sslContext = sslContextBuilder.build();
} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
throw Throwables.propagate(e);
}
OkHttpClient.Builder client = new OkHttpClient().newBuilder().sslSocketFactory(sslContext.getSocketFactory()).connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).followSslRedirects(false);
client.followRedirects(false);
client.retryOnConnectionFailure(false);
// Won't use cookies and a client certificate at once.
if (!usingClientCert) {
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.cookieJar(new JavaNetCookieJar(cookieManager));
}
for (Interceptor interceptor : requestInterceptors) {
client.networkInterceptors().add(interceptor);
}
return client.build();
}
use of okhttp3.JavaNetCookieJar in project AntennaPod by AntennaPod.
the class AntennapodHttpClient method newBuilder.
/**
* Creates a new HTTP client. Most users should just use
* getHttpClient() to get the standard AntennaPod client,
* but sometimes it's necessary for others to have their own
* copy so that the clients don't share state.
* @return http client
*/
@NonNull
public static OkHttpClient.Builder newBuilder() {
Log.d(TAG, "Creating new instance of HTTP client");
System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// detect 301 Moved permanently and 308 Permanent Redirect
builder.networkInterceptors().add(chain -> {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == HttpURLConnection.HTTP_MOVED_PERM || response.code() == StatusLine.HTTP_PERM_REDIRECT) {
String location = response.header("Location");
if (location.startsWith("/")) {
HttpUrl url = request.url();
location = url.scheme() + "://" + url.host() + location;
} else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
HttpUrl url = request.url();
String path = url.encodedPath();
String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
location = url.scheme() + "://" + url.host() + newPath;
}
try {
DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
}
return response;
});
// set cookie handler
CookieManager cm = new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
builder.cookieJar(new JavaNetCookieJar(cm));
// set timeouts
builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
// configure redirects
builder.followRedirects(true);
builder.followSslRedirects(true);
ProxyConfig config = UserPreferences.getProxyConfig();
if (config.type != Proxy.Type.DIRECT) {
int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
Proxy proxy = new Proxy(config.type, address);
builder.proxy(proxy);
if (!TextUtils.isEmpty(config.username)) {
String credentials = Credentials.basic(config.username, config.password);
builder.interceptors().add(chain -> {
Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
return chain.proceed(request);
});
}
}
if (16 <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < 21) {
builder.sslSocketFactory(new CustomSslSocketFactory(), trustManager());
}
return builder;
}
use of okhttp3.JavaNetCookieJar in project keywhiz by square.
the class ClientUtils method sslOkHttpClient.
/**
* Creates a {@link OkHttpClient} to start a TLS connection.
*
* @param devTrustStore if not null, uses the provided TrustStore instead of whatever is
* configured in the JVM. This is a convenient way to allow developers to
* start playing with Keywhiz right away. This option should not be used in
* production systems.
* @param cookies list of cookies to include in the client.
* @return new http client.
*/
public static OkHttpClient sslOkHttpClient(@Nullable KeyStore devTrustStore, List<HttpCookie> cookies) {
checkNotNull(cookies);
SSLContext sslContext;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(devTrustStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
throw Throwables.propagate(e);
}
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder client = new OkHttpClient().newBuilder().sslSocketFactory(socketFactory).connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).followSslRedirects(false);
client.retryOnConnectionFailure(false);
client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
cookies.forEach(c -> getCookieManager().getCookieStore().add(null, c));
client.cookieJar(new JavaNetCookieJar(getCookieManager()));
return client.build();
}
use of okhttp3.JavaNetCookieJar in project okhttp by square.
the class CookiesTest method testCookiesSentIgnoresCase.
@Test
public void testCookiesSentIgnoresCase() throws Exception {
client = client.newBuilder().cookieJar(new JavaNetCookieJar(new CookieManager() {
@Override
public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> result = new LinkedHashMap<>();
result.put("COOKIE", Collections.singletonList("Bar=bar"));
result.put("cooKIE2", Collections.singletonList("Baz=baz"));
return result;
}
})).build();
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
server.start();
get(server.url("/"));
RecordedRequest request = server.takeRequest();
assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
assertNull(request.getHeader("Cookie2"));
assertNull(request.getHeader("Quux"));
}
use of okhttp3.JavaNetCookieJar in project okhttp by square.
the class CookiesTest method receiveAndSendMultipleCookies.
@Test
public void receiveAndSendMultipleCookies() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().addHeader("Set-Cookie", "a=android").addHeader("Set-Cookie", "b=banana"));
server.enqueue(new MockResponse());
server.start();
CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
client = client.newBuilder().cookieJar(new JavaNetCookieJar(cookieManager)).build();
get(urlWithIpAddress(server, "/"));
RecordedRequest request1 = server.takeRequest();
assertNull(request1.getHeader("Cookie"));
get(urlWithIpAddress(server, "/"));
RecordedRequest request2 = server.takeRequest();
assertEquals("a=android; b=banana", request2.getHeader("Cookie"));
}
Aggregations