List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:com.ddling.client.smtp.SmtpClient.java
/** * ?smtp/* w w w . j a va2s . c om*/ */ private void initClient() { logger.info("Connect to " + server + " At port " + port); try { socket = new Socket(server, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); int response = getResponse(); if (response == 220) { logger.info("Connect to " + server + " done!"); } } catch (IOException e) { logger.error(e); } }
From source file:io.selendroid.android.impl.DefaultAndroidEmulator.java
private static Map<String, Integer> mapDeviceNamesToSerial() { Map<String, Integer> mapping = new HashMap<String, Integer>(); CommandLine command = new CommandLine(AndroidSdk.adb()); command.addArgument("devices"); Scanner scanner;/* ww w .ja v a 2 s . co m*/ try { scanner = new Scanner(ShellCommand.exec(command)); } catch (ShellCommandException e) { return mapping; } while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d"); Matcher matcher = pattern.matcher(line); if (matcher.find()) { String serial = matcher.group(0); Integer port = Integer.valueOf(serial.replaceAll("emulator-", "")); TelnetClient client = null; try { client = new TelnetClient(port); String avdName = client.sendCommand("avd name"); mapping.put(avdName, port); } catch (AndroidDeviceException e) { // ignore } finally { if (client != null) { client.close(); } } Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { throw new AndroidDeviceException("error"); } out.write("avd name\r\n"); out.flush(); in.readLine();// OK String avdName = in.readLine(); mapping.put(avdName, port); } catch (Exception e) { // ignore } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // do nothing } } } } scanner.close(); return mapping; }
From source file:com.symbian.driver.plugins.reboot.Activator.java
/** * @param switchState//from w ww . j a v a 2 s. c om * @throws IOException */ private synchronized void switchOp(String switchState) throws IOException { LOGGER.log(Level.INFO, "Activator::switchOp"); // Alternative being "TelnetSwitch" if (method.compareToIgnoreCase("PortTalk") == 0)// ATX power { String state = switchState == "2" ? "OFF" : "ON"; File hardwareSwitchFile = JarUtils.extractResource(Activator.class, "/resource/HardwareSwitch.exe"); if (hardwareSwitchFile.isFile()) { Process p = Runtime.getRuntime() .exec("cmd.exe /c " + hardwareSwitchFile.getAbsolutePath() + " " + state); BufferedReader iBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream())); String lOutput = null; StringBuffer iOutputBuffer = new StringBuffer(); while ((lOutput = iBufferedReader.readLine()) != null) { lOutput += System.getProperty("line.separator"); iOutputBuffer.append(lOutput); // Parse for errors and redirect to appropriate buffer. } LOGGER.info(iOutputBuffer.toString()); } else { LOGGER.warning(hardwareSwitchFile.getAbsolutePath() + " was not found"); } } else { String responseLine = ""; String[] states = { "User Name :", "Password :", "Control Console", "Device Manager", "Outlet Management", "Outlet Control/Configuration", "Outlet " + outletNo, "Control Outlet", "Immediate Off", "Press <ENTER> to continue..." }; String[] answers = { userName, password, "1", "2", "1", outletNo, "1", switchState, "YES", "\n" }; Socket sock = new Socket(hostAddr, 23); PrintWriter dataToTelnetServer = new PrintWriter(sock.getOutputStream(), true); BufferedReader dataFromTelnetServer = new BufferedReader(new InputStreamReader(sock.getInputStream())); // start the state machine... int state = 0; long lastStateChng = System.currentTimeMillis(); while (state < states.length) { while (dataFromTelnetServer.ready()) { char nextChar = (char) dataFromTelnetServer.read(); responseLine += nextChar; } LOGGER.log(Level.FINE, responseLine); if (responseLine.contains(states[state])) // sort of on { LOGGER.log(Level.FINE, "answers[" + state + "]:" + answers[state]); dataToTelnetServer.println(answers[state]); state++; lastStateChng = System.currentTimeMillis(); continue; } if ((System.currentTimeMillis() - lastStateChng) > 10000) { // too much time since last change of state... // we have lost the connection... LOGGER.log(Level.SEVERE, "Lost telnet connection"); break; } } responseLine = ""; dataToTelnetServer.flush(); dataToTelnetServer.close(); dataFromTelnetServer.close(); sock.close(); } }
From source file:android.net.http.HttpsConnection.java
/** * Opens the connection to a http server or proxy. * * @return the opened low level connection * @throws IOException if the connection fails for any reason. *//*w w w . java2s . co m*/ @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { SSLSocket sslSock = null; if (mProxyHost != null) { // If we have a proxy set, we first send a CONNECT request // to the proxy; if the proxy returns 200 OK, we negotiate // a secure connection to the target server via the proxy. // If the request fails, we drop it, but provide the event // handler with the response status and headers. The event // handler is then responsible for cancelling the load or // issueing a new request. AndroidHttpClientConnection proxyConnection = null; Socket proxySock = null; try { proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort()); proxySock.setSoTimeout(60 * 1000); proxyConnection = new AndroidHttpClientConnection(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(params, 8192); proxyConnection.bind(proxySock, params); } catch (IOException e) { if (proxyConnection != null) { proxyConnection.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to establish a connection to the proxy"; } throw new IOException(errorMessage); } StatusLine statusLine = null; int statusCode = 0; Headers headers = new Headers(); try { BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString()); // add all 'proxy' headers from the original request for (Header h : req.mHttpRequest.getAllHeaders()) { String headerName = h.getName().toLowerCase(); if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) { proxyReq.addHeader(h); } } proxyConnection.sendRequestHeader(proxyReq); proxyConnection.flush(); // it is possible to receive informational status // codes prior to receiving actual headers; // all those status codes are smaller than OK 200 // a loop is a standard way of dealing with them do { statusLine = proxyConnection.parseResponseHeader(headers); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); } catch (ParseException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (HttpException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (IOException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } if (statusCode == HttpStatus.SC_OK) { try { sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } else { // if the code is not OK, inform the event handler ProtocolVersion version = statusLine.getProtocolVersion(); req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase()); req.mEventHandler.headers(headers); req.mEventHandler.endData(); proxyConnection.close(); // here, we return null to indicate that the original // request needs to be dropped return null; } } else { // if we do not have a proxy, we simply connect to the host try { sslSock = (SSLSocket) getSocketFactory().createSocket(); sslSock.setSoTimeout(SOCKET_TIMEOUT); sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort())); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } // do handshake and validate server certificates SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); // Inform the user if there is a problem if (error != null) { // handleSslErrorRequest may immediately unsuspend if it wants to // allow the certificate anyway. // So we mark the connection as suspended, call handleSslErrorRequest // then check if we're still suspended and only wait if we actually // need to. synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = req.getEventHandler().handleSslErrorRequest(error); if (!canHandle) { throw new IOException("failed to handle " + error); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. sslSock.close(); throw new SSLConnectionClosedByUserException("connection closed by the user"); } } } // All went well, we have an open, verified connection. AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sslSock, params); return conn; }
From source file:android.net.http.HttpsConnection.java
/** * Opens the connection to a http server or proxy. * * @return the opened low level connection * @throws IOException if the connection fails for any reason. *//*w ww.j a va2 s.c o m*/ @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { SSLSocket sslSock = null; if (mProxyHost != null) { // If we have a proxy set, we first send a CONNECT request // to the proxy; if the proxy returns 200 OK, we negotiate // a secure connection to the target server via the proxy. // If the request fails, we drop it, but provide the event // handler with the response status and headers. The event // handler is then responsible for cancelling the load or // issueing a new request. AndroidHttpClientConnection proxyConnection = null; Socket proxySock = null; try { proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort()); proxySock.setSoTimeout(60 * 1000); proxyConnection = new AndroidHttpClientConnection(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(params, 8192); proxyConnection.bind(proxySock, params); } catch (IOException e) { if (proxyConnection != null) { proxyConnection.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to establish a connection to the proxy"; } throw new IOException(errorMessage); } StatusLine statusLine = null; int statusCode = 0; Headers headers = new Headers(); try { BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString()); // add all 'proxy' headers from the original request for (Header h : req.mHttpRequest.getAllHeaders()) { String headerName = h.getName().toLowerCase(); if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) { proxyReq.addHeader(h); } } proxyConnection.sendRequestHeader(proxyReq); proxyConnection.flush(); // it is possible to receive informational status // codes prior to receiving actual headers; // all those status codes are smaller than OK 200 // a loop is a standard way of dealing with them do { statusLine = proxyConnection.parseResponseHeader(headers); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); } catch (ParseException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (HttpException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (IOException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } if (statusCode == HttpStatus.SC_OK) { try { sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } else { // if the code is not OK, inform the event handler ProtocolVersion version = statusLine.getProtocolVersion(); req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase()); req.mEventHandler.headers(headers); req.mEventHandler.endData(); proxyConnection.close(); // here, we return null to indicate that the original // request needs to be dropped return null; } } else { // if we do not have a proxy, we simply connect to the host try { sslSock = (SSLSocket) getSocketFactory().createSocket(); sslSock.setSoTimeout(SOCKET_TIMEOUT); sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort())); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } // do handshake and validate server certificates SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); EventHandler eventHandler = req.getEventHandler(); // Update the certificate info (to be consistent, it is better to do it // here, before we start handling SSL errors, if any) eventHandler.certificate(mCertificate); // Inform the user if there is a problem if (error != null) { // handleSslErrorRequest may immediately unsuspend if it wants to // allow the certificate anyway. // So we mark the connection as suspended, call handleSslErrorRequest // then check if we're still suspended and only wait if we actually // need to. synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = eventHandler.handleSslErrorRequest(error); if (!canHandle) { throw new IOException("failed to handle " + error); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. sslSock.close(); throw new SSLConnectionClosedByUserException("connection closed by the user"); } } } // All went well, we have an open, verified connection. AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sslSock, params); return conn; }
From source file:org.cloudfoundry.identity.uaa.ServerRunning.java
private boolean connectionAvailable() { logger.info("Testing connectivity for " + hostName + ":" + port); try (Socket socket = new Socket(hostName, port)) { logger.info("Connectivity test succeeded for " + hostName + ":" + port); return true; } catch (IOException e) { logger.warn("Connectivity test failed for " + hostName + ":" + port, e); return false; }/*w w w .j av a 2 s .c o m*/ }
From source file:com.adito.jdbc.hsqldb.EmbeddedHSQLDBServer.java
void waitForServer() { if (!testedConnection && serverMode) { Socket s = null;/*from ww w .j a v a2s.com*/ String addr = server.getAddress().equals("0.0.0.0") ? "127.0.0.1" : server.getAddress(); if (log.isInfoEnabled()) log.info("Waiting for HSQLDB to start accepting connections on " + addr + ":" + server.getPort()); for (int i = 0; i < 30; i++) { try { s = new Socket(addr, server.getPort()); break; } catch (IOException ioe) { try { Thread.sleep(1000); } catch (InterruptedException ie) { } } } if (s == null) { throw new IllegalStateException("The HSQLDB server is not accepting connections after 30 seconds."); } else { testedConnection = true; if (log.isInfoEnabled()) log.info("HSQLDB is now accepting connections."); try { s.close(); } catch (IOException ioe) { } } } }
From source file:SimpleFTP.java
/** * Sends a file to be stored on the FTP server. Returns true if the file * transfer was successful. The file is sent in passive mode to avoid NAT or * firewall problems at the client end.// www . jav a 2s . co m */ public synchronized boolean stor(InputStream inputStream, String filename) throws IOException { BufferedInputStream input = new BufferedInputStream(inputStream); sendLine("PASV"); String response = readLine(); if (!response.startsWith("227 ")) { throw new IOException("SimpleFTP could not request passive mode: " + response); } String ip = null; int port = -1; int opening = response.indexOf('('); int closing = response.indexOf(')', opening + 1); if (closing > 0) { String dataLink = response.substring(opening + 1, closing); StringTokenizer tokenizer = new StringTokenizer(dataLink, ","); try { ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken(); port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken()); } catch (Exception e) { throw new IOException("SimpleFTP received bad data link information: " + response); } } sendLine("STOR " + filename); Socket dataSocket = new Socket(ip, port); response = readLine(); if (!response.startsWith("125 ")) { //if (!response.startsWith("150 ")) { throw new IOException("SimpleFTP was not allowed to send the file: " + response); } BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream()); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } output.flush(); output.close(); input.close(); response = readLine(); return response.startsWith("226 "); }
From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java
/** * @param key/*from w w w. j a va 2s.c o m*/ * @param value * @throws IOException */ private void send(final String key, final String value) throws IOException { final long start = System.currentTimeMillis(); final StringBuilder message = new StringBuilder(head); message.append(encodeBase64(key)); message.append(middle); message.append(encodeBase64(value == null ? "" : value)); message.append(tail); logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value)); logger.trace(bundle.getString("zabbix-sender-detailed-message", message)); Socket socket = null; OutputStreamWriter out = null; InputStream in = null; try { socket = new Socket(zabbixServer, zabbixPort); socket.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(socket.getOutputStream()); out.write(message.toString()); out.flush(); in = socket.getInputStream(); final int read = in.read(response); final String resp = new String(response); logger.debug(bundle.getString("zabbix-sender-received-response", resp)); if (read != 2 || response[0] != 'O' || response[1] != 'K') { logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp)); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (socket != null) { socket.close(); } } final long elapsed = System.currentTimeMillis() - start; logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed)); }
From source file:android.net.http.HttpsConnection.java
/** * Opens the connection to a http server or proxy. * * @return the opened low level connection * @throws IOException if the connection fails for any reason. *//*from w w w . j a va 2 s . co m*/ @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { SSLSocket sslSock = null; if (mProxyHost != null) { // If we have a proxy set, we first send a CONNECT request // to the proxy; if the proxy returns 200 OK, we negotiate // a secure connection to the target server via the proxy. // If the request fails, we drop it, but provide the event // handler with the response status and headers. The event // handler is then responsible for cancelling the load or // issueing a new request. AndroidHttpClientConnection proxyConnection = null; Socket proxySock = null; try { proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort()); proxySock.setSoTimeout(60 * 1000); proxyConnection = new AndroidHttpClientConnection(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(params, 8192); proxyConnection.bind(proxySock, params); } catch (IOException e) { if (proxyConnection != null) { proxyConnection.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to establish a connection to the proxy"; } throw new IOException(errorMessage); } StatusLine statusLine = null; int statusCode = 0; Headers headers = new Headers(); try { BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString()); // add all 'proxy' headers from the original request, we also need // to add 'host' header unless we want proxy to answer us with a // 400 Bad Request for (Header h : req.mHttpRequest.getAllHeaders()) { String headerName = h.getName().toLowerCase(Locale.ROOT); if (headerName.startsWith("proxy") || headerName.equals("keep-alive") || headerName.equals("host")) { proxyReq.addHeader(h); } } proxyConnection.sendRequestHeader(proxyReq); proxyConnection.flush(); // it is possible to receive informational status // codes prior to receiving actual headers; // all those status codes are smaller than OK 200 // a loop is a standard way of dealing with them do { statusLine = proxyConnection.parseResponseHeader(headers); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); } catch (ParseException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (HttpException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (IOException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } if (statusCode == HttpStatus.SC_OK) { try { sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } else { // if the code is not OK, inform the event handler ProtocolVersion version = statusLine.getProtocolVersion(); req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase()); req.mEventHandler.headers(headers); req.mEventHandler.endData(); proxyConnection.close(); // here, we return null to indicate that the original // request needs to be dropped return null; } } else { // if we do not have a proxy, we simply connect to the host try { sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort()); sslSock.setSoTimeout(SOCKET_TIMEOUT); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } // do handshake and validate server certificates SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); // Inform the user if there is a problem if (error != null) { // handleSslErrorRequest may immediately unsuspend if it wants to // allow the certificate anyway. // So we mark the connection as suspended, call handleSslErrorRequest // then check if we're still suspended and only wait if we actually // need to. synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = req.getEventHandler().handleSslErrorRequest(error); if (!canHandle) { throw new IOException("failed to handle " + error); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. sslSock.close(); throw new SSLConnectionClosedByUserException("connection closed by the user"); } } } // All went well, we have an open, verified connection. AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sslSock, params); return conn; }