use of okhttp3.OkHttpClient in project couchbase-lite-android by couchbase.
the class ReplicatorWithSyncGatewayDBTest method sendRequestToEndpoint.
JSONObject sendRequestToEndpoint(URLEndpoint endpoint, String method, String path, String mediaType, byte[] body) throws Exception {
URI endpointURI = endpoint.getURL();
String _scheme = endpointURI.getScheme().equals(URLEndpoint.kURLEndpointTLSScheme) ? "https" : "http";
String _host = endpointURI.getHost();
int _port = endpointURI.getPort() + 1;
path = (path != null) ? (path.startsWith("/") ? path : "/" + path) : "";
String _path = String.format(Locale.ENGLISH, "%s%s", endpointURI.getPath(), path);
URI uri = new URI(_scheme, null, _host, _port, _path, null, null);
OkHttpClient client = new OkHttpClient();
okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(uri.toURL());
RequestBody requestBody = null;
if (body != null && body instanceof byte[])
requestBody = RequestBody.create(MediaType.parse(mediaType), body);
builder.method(method, requestBody);
okhttp3.Request request = builder.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i(TAG, "Send request succeeded; URL=<%s>, Method=<%s>, Status=%d", uri, method, response.code());
return new JSONObject(response.body().string());
} else {
// error
Log.e(TAG, "Failed to send request; URL=<%s>, Method=<%s>, Status=%d, Error=%s", uri, method, response.code(), response.message());
return null;
}
}
use of okhttp3.OkHttpClient in project couchbase-lite-android by couchbase.
the class ReplicatorWithSyncGatewayTest method getSessionAuthenticatorFromSG.
SessionAuthenticator getSessionAuthenticatorFromSG() throws Exception {
// Obtain Sync-Gateway Session ID
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String url = String.format(Locale.ENGLISH, "http://%s:4985/seekrit/_session", config.remoteHost());
RequestBody body = RequestBody.create(JSON, "{\"name\": \"pupshaw\"}");
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
String respBody = response.body().string();
Log.e(TAG, "json string -> " + respBody);
JSONObject json = new JSONObject(respBody);
return new SessionAuthenticator(json.getString("session_id"), json.getString("cookie_name"));
}
use of okhttp3.OkHttpClient in project couchbase-lite-android by couchbase.
the class CBLWebSocket method setupOkHttpClient.
// -------------------------------------------------------------------------
// private methods
// -------------------------------------------------------------------------
private OkHttpClient setupOkHttpClient() throws GeneralSecurityException {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// timeouts
builder.connectTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS);
// redirection
builder.followRedirects(true).followSslRedirects(true);
// authenticator
Authenticator authenticator = setupAuthenticator();
if (authenticator != null)
builder.authenticator(authenticator);
// trusted certificate (pinned certificate)
setupTrustedCertificate(builder);
return builder.build();
}
use of okhttp3.OkHttpClient in project BBS-Android by bdpqchen.
the class RxDoHttpClient method getUnsafeOkHttpClient.
public static OkHttpClient.Builder getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
okHttpClient.sslSocketFactory(sslSocketFactory);
okHttpClient.protocols(Collections.singletonList(Protocol.HTTP_1_1));
okHttpClient.hostnameVerifier((hostname, session) -> true);
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of okhttp3.OkHttpClient in project bitcoin-wallet by bitcoin-wallet.
the class DynamicFeeLoader method fetchDynamicFees.
private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile, final String userAgent) {
final Stopwatch watch = Stopwatch.createStarted();
final Request.Builder request = new Request.Builder();
request.url(url);
request.header("User-Agent", userAgent);
if (targetFile.exists())
request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));
OkHttpClient.Builder httpClientBuilder = Constants.HTTP_CLIENT.newBuilder();
httpClientBuilder.connectTimeout(5, TimeUnit.SECONDS);
httpClientBuilder.writeTimeout(5, TimeUnit.SECONDS);
httpClientBuilder.readTimeout(5, TimeUnit.SECONDS);
final OkHttpClient httpClient = httpClientBuilder.build();
final Call call = httpClient.newCall(request.build());
try {
final Response response = call.execute();
final int status = response.code();
if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
log.info("Dynamic fees not modified at {}, took {}", url, watch);
} else if (status == HttpURLConnection.HTTP_OK) {
final ResponseBody body = response.body();
final FileOutputStream os = new FileOutputStream(tempFile);
Io.copy(body.byteStream(), os);
os.close();
final Date lastModified = response.headers().getDate("Last-Modified");
if (lastModified != null)
tempFile.setLastModified(lastModified.getTime());
body.close();
if (!tempFile.renameTo(targetFile))
throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
watch.stop();
log.info("Dynamic fees fetched from {}, took {}", url, watch);
} else {
log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
}
} catch (final Exception x) {
log.warn("Problem when fetching dynamic fees rates from " + url, x);
}
}
Aggregations