forked from marianobarrios/tls-channel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleBlockingClient.java
54 lines (41 loc) · 1.9 KB
/
SimpleBlockingClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package tlschannel.example;
import tlschannel.ClientTlsChannel;
import tlschannel.TlsChannel;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
/**
* Client example. Connects to a public TLS reporting service.
*/
public class SimpleBlockingClient {
private static final Charset utf8 = StandardCharsets.UTF_8;
public static final String domain = "www.howsmyssl.com";
public static final String httpLine =
"GET https://www.howsmyssl.com/a/check HTTP/1.0\nHost: www.howsmyssl.com\n\n";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
// initialize the SSLContext, a configuration holder, reusable object
SSLContext sslContext = SSLContext.getDefault();
// connect raw socket channel normally
try (SocketChannel rawChannel = SocketChannel.open()) {
rawChannel.connect(new InetSocketAddress(domain, 443));
// create TlsChannel builder, combining the raw channel and the SSLEngine, using minimal options
ClientTlsChannel.Builder builder = ClientTlsChannel.newBuilder(rawChannel, sslContext);
// instantiate TlsChannel
try (TlsChannel tlsChannel = builder.build()) {
// do HTTP interaction and print result
tlsChannel.write(ByteBuffer.wrap(httpLine.getBytes()));
ByteBuffer res = ByteBuffer.allocate(10000);
// being HTTP 1.0, the server will just close the connection at the end
while (tlsChannel.read(res) != -1)
;
res.flip();
System.out.println(utf8.decode(res).toString());
}
}
}
}