LoginSignup
0
0

More than 1 year has passed since last update.

JavaのSSLSocketを使う(クライアント編1)

Last updated at Posted at 2021-07-22

はじめに

クライアント側の第1段階として、標準のtruststoreを使ってSSL通信する。

概要

サーバ側と同様にSSLContextのインスタンスを取得して、そこからSocketFactoryを得る。
SocketFactoryからSSLSocketが得られて、後は普通のSocketと同じように通信できる。

標準SSLContext

標準のtruststoreを使うSSLContextの取得は簡単で、getDefault() すれば良い。
コードとしては、これだけになる。

import javax.net.ssl.SSLContext;

   .
   .
   .

SSLContext ctx = SSLContext.getDefault();

SocketFactory

SSLContextが取得できればこちらも簡単。前述の ctx を使って getSocketFactory() すれば良い。

import javax.net.ssl.SSLSocketFactory;

   .
   .
   .

SSLSocketFactory socketfactory = ctx.getSocketFactory();

Socketの取得と通信

ここまでのところをまとめて、通信部分を追加してみる。
実行すると qiita.com のHTMLが出力される。

package sslclient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.net.Socket;
import java.io.OutputStream;
import java.io.InputStream;

public class App
{
    private static SSLContext secureSocketContext;
    private static SSLSocketFactory secureSocketFactory;

    private static void initSSL()
    {
        try {
            secureSocketContext = SSLContext.getDefault();
            secureSocketFactory = secureSocketContext.getSocketFactory();
        }
        catch (Exception e) {
            System.out.println("initSSL exception: " + e.toString());
        }
    }

    public static void main(String[] args)
    {
        initSSL();
        try {
            Socket sock = secureSocketFactory.createSocket("qiita.com", 443);
            OutputStream os = sock.getOutputStream();
            InputStream is = sock.getInputStream();
            String request_str = "GET / HTTP/1.1\r\nHost: qiita.com:443\r\n\r\n";
            os.write(request_str.getBytes());
            byte[] resp_buf = new byte[1024 * 1024 * 8];
            int resp_len = is.read(resp_buf);
            if (0 < resp_len) {
                String resp_str = new String(resp_buf, 0, resp_len);
                System.out.println(resp_str);
            }
        }
        catch (Exception e) {
            System.out.println("exception: " + e.toString());
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0