use of javax.net.ssl.SSLSocketFactory in project Talon-for-Twitter by klinker24.
the class GetLocations method getJsonResponse.
public static String getJsonResponse() {
String json = "";
try {
String oauth_token = "";
String oauth_token_secret = "";
// generate authorization header
String get_or_post = "GET";
String oauth_signature_method = "HMAC-SHA1";
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
// any relatively random alphanumeric string will work here
String oauth_nonce = uuid_string;
// get the timestamp
Calendar tempcal = Calendar.getInstance();
// get current time in milliseconds
long ts = tempcal.getTimeInMillis();
// then divide by 1000 to get seconds
String oauth_timestamp = (new Long(ts / 1000)).toString();
// the parameter string must be in alphabetical order, "text" parameter added at end
String parameter_string = "oauth_consumer_key=" + "" + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
String twitter_endpoint = "https://api.twitter.com/1.1/trends/available.json";
String twitter_endpoint_host = "api.twitter.com";
String twitter_endpoint_path = "/1.1/trends/available.json";
String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
String oauth_signature = computeSignature(signature_base_string, "" + "&" + encode(oauth_token_secret));
String authorization_header_string = "OAuth oauth_consumer_key=\"" + "V9yijGrKf79jlYi0l3ekpA" + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
HttpProtocolParams.setUseExpectContinue(params, false);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost(twitter_endpoint_host, 443);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, null, null);
SSLSocketFactory ssf = sslcontext.getSocketFactory();
Socket socket = ssf.createSocket();
socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
conn.bind(socket, params);
BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path);
request2.setParams(params);
request2.addHeader("Authorization", authorization_header_string);
httpexecutor.preProcess(request2, httpproc, context);
HttpResponse response2 = httpexecutor.execute(request2, conn, context);
response2.setParams(params);
httpexecutor.postProcess(response2, httpproc, context);
json = EntityUtils.toString(response2.getEntity());
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
use of javax.net.ssl.SSLSocketFactory 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 javax.net.ssl.SSLSocketFactory in project okhttp by square.
the class MockWebServer method processHandshakeFailure.
private void processHandshakeFailure(Socket raw) throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { UNTRUSTED_TRUST_MANAGER }, new SecureRandom());
SSLSocketFactory sslSocketFactory = context.getSocketFactory();
SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
try {
// we're testing a handshake failure
socket.startHandshake();
throw new AssertionError();
} catch (IOException expected) {
}
socket.close();
}
use of javax.net.ssl.SSLSocketFactory in project okhttp by square.
the class OkHttpAsync method prepare.
@Override
public void prepare(final Benchmark benchmark) {
concurrencyLevel = benchmark.concurrencyLevel;
targetBacklog = benchmark.targetBacklog;
client = new OkHttpClient.Builder().protocols(benchmark.protocols).dispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()))).build();
if (benchmark.tls) {
SslClient sslClient = SslClient.localhost();
SSLSocketFactory socketFactory = sslClient.socketFactory;
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession session) {
return true;
}
};
client = client.newBuilder().sslSocketFactory(socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build();
}
callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Failed: " + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long total = SynchronousHttpClient.readAllAndClose(body.byteStream());
long finish = System.nanoTime();
if (VERBOSE) {
long start = (Long) response.request().tag();
System.out.printf("Transferred % 8d bytes in %4d ms%n", total, TimeUnit.NANOSECONDS.toMillis(finish - start));
}
requestsInFlight.decrementAndGet();
}
};
}
use of javax.net.ssl.SSLSocketFactory in project okhttp by square.
the class ClientAuthTest method clientAuthForWants.
@Test
public void clientAuthForWants() throws Exception {
OkHttpClient client = buildClient(clientCert, clientIntermediateCa);
SSLSocketFactory socketFactory = buildServerSslSocketFactory(ClientAuth.WANTS);
server.useHttps(socketFactory, false);
server.enqueue(new MockResponse().setBody("abc"));
Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute();
assertEquals(new X500Principal("CN=localhost"), response.handshake().peerPrincipal());
assertEquals(new X500Principal("CN=Jethro Willis"), response.handshake().localPrincipal());
assertEquals("abc", response.body().string());
}
Aggregations