Android Studio Java SSL套接字客户端

时间:2018-09-12 20:05:28

标签: java android client sslsocketfactory

我尝试为服务器连接构建客户端。 但是,如果我尝试在Android Studio中构建此客户端,那我将成为致命的例外: android.os.NetworkOnMainThreadException。 我搜索了不同的解决方案,但没有任何效果。我希望你能帮助我。

INTERNET-PERMISSION已在清单中显示

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.oliverlenk.pmt, PID: 2387
              android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
                  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
                  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
                  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
                  at java.net.Socket.connect(Socket.java:605)
                  at java.net.Socket.connect(Socket.java:554)
                  at java.net.Socket.<init>(Socket.java:431)
                  at java.net.Socket.<init>(Socket.java:210)
                  at com.example.oliverlenk.pmt.MainActivity$1.onClick(MainActivity.java:84)
                  at android.view.View.performClick(View.java:5637)
                  at android.view.View$PerformClick.run(View.java:22429)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

应用程序终止。

这是我的Java代码:

公共类MainActivity扩展了活动{

// Inistailierung
Button Send;
EditText IP;
EditText Port;
TextView Answer;
EditText Message;

private String ip_address;
private int port = 11880;
private SSLSocket socket = null;
private BufferedReader in = null;
private BufferedWriter out = null;
private final String TAG = "TAG";
private char keystorepass[] = "key12345".toCharArray();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Send = (Button) findViewById(R.id.btnSend);
    IP = (EditText) findViewById(R.id.etIP);
    Port = (EditText) findViewById(R.id.etPort);
    Answer = (TextView) findViewById(R.id.tvAnswer);
    Message = (EditText) findViewById(R.id.etMessage);


    Send.setClickable(true);
    Send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (IP.getText().toString().equals(null) || Port.getText().toString().equals(null)){
                Toast.makeText(v.getContext(), "Bitte IP und Port eingeben", Toast.LENGTH_LONG).show();
            }else {
                String temp = Message.getText().toString();
                if (temp == null){
                    temp = "Es wurde keine Nachricht eingegeben";
                }
                port = Integer.parseInt(Port.getText().toString());
                ip_address = IP.getText().toString();

                try {
                    KeyStore ks = KeyStore.getInstance("BKS");
                    InputStream keyin = v.getResources().openRawResource(R.raw.neuserverkeypem);
                    ks.load(keyin,keystorepass);
                    org.apache.http.conn.ssl.SSLSocketFactory socketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(ks);
                    socketFactory.setHostnameVerifier(socketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                    socket = (SSLSocket)
                            socketFactory.createSocket(new Socket(ip_address,port), ip_address, port, false);
                    socket.startHandshake();

                    printServerCertificate(socket);
                    printSocketInfo(socket);

                    out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    chat(temp);
                } catch (UnknownHostException e) {
                    Toast.makeText(v.getContext(), "Unknown host", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"Unknown host");
                    //System.exit(1);
                } catch  (IOException e) {
                    Toast.makeText(v.getContext(), "No I/O", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"No I/O");
                    e.printStackTrace();
                    //System.exit(1);
                } catch (KeyStoreException e) {
                    Toast.makeText(v.getContext(), "Keystore ks error", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"Keystore ks error");
                    //System.exit(-1);
                } catch (NoSuchAlgorithmException e) {
                    Toast.makeText(v.getContext(), "No such algorithm for ks.load", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"No such algorithm for ks.load");
                    e.printStackTrace();
                    //System.exit(-1);
                } catch (CertificateException e) {
                    Toast.makeText(v.getContext(), "certificate missing", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"certificate missing");
                    e.printStackTrace();
                    //System.exit(-1);
                } catch (UnrecoverableKeyException e) {
                    Toast.makeText(v.getContext(), "UnrecoverableKeyException", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"unrecoverableKeyException");
                    e.printStackTrace();
                    //System.exit(-1);
                } catch (KeyManagementException e) {
                    Toast.makeText(v.getContext(), "KeyManagementException", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"key management exception");
                    e.printStackTrace();
                    //System.exit(-1);
                }
            }
        }
    });



}
private void printServerCertificate(SSLSocket socket) {
    try {
        Certificate[] serverCerts =
                socket.getSession().getPeerCertificates();
        for (int i = 0; i < serverCerts.length; i++) {
            Certificate myCert = serverCerts[i];
            Log.i(TAG,"====Certificate:" + (i+1) + "====");
            Log.i(TAG,"-Public Key-\n" + myCert.getPublicKey());
            Log.i(TAG,"-Certificate Type-\n " + myCert.getType());

            System.out.println();
        }
    } catch (SSLPeerUnverifiedException e) {
        Log.i(TAG,"Could not verify peer");
        e.printStackTrace();
        System.exit(-1);
    }
}
private void printSocketInfo(SSLSocket s) {
    Log.i(TAG,"Socket class: "+s.getClass());
    Log.i(TAG,"   Remote address = "
            +s.getInetAddress().toString());
    Log.i(TAG,"   Remote port = "+s.getPort());
    Log.i(TAG,"   Local socket address = "
            +s.getLocalSocketAddress().toString());
    Log.i(TAG,"   Local address = "
            +s.getLocalAddress().toString());
    Log.i(TAG,"   Local port = "+s.getLocalPort());
    Log.i(TAG,"   Need client authentication = "
            +s.getNeedClientAuth());
    SSLSession ss = s.getSession();
    Log.i(TAG,"   Cipher suite = "+ss.getCipherSuite());
    Log.i(TAG,"   Protocol = "+ss.getProtocol());
}

public void chat(String temp){
    String message = temp;
    String line = "";
    // send id of the device to match with the image
    try {
        out.write(message+"\n");
        out.flush();
    } catch (IOException e2) {
        Log.i(TAG,"Read failed");
        System.exit(1);
    }
    // receive a ready command from the server
    try {
        line = in.readLine();
        Answer.setText("SERVER SAID: "+line);
        //Log.i(TAG,line);
    } catch (IOException e1) {
        Log.i(TAG,"Read failed");
        System.exit(1);
    }
}

}

0 个答案:

没有答案