I have written a simple HTTPS client in Java to POST some data to a server. The server has a valid certificate signed by a trusted CA, so I didn't have to mess with any keystores or self-signed certificates. Here is the code:
try
{
String data = "This is a test";
SSLSocketFactory sslFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://my.server.name");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
InputStream ins = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
String result;
while( (inputLine = in.readLine()) != null )
result += inputLine;
in.close();
}
catch( Exception e )
{
e.printStackTrace();
}
This code works fine when run as part of a command line Java program, but it does not work correctly on Android (at least not in the emulator). I have traced the problem to this line:
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
The call to conn.getOutputStream() seems to hang until the connection times out on the server. It does not throw an exception. It just waits indefinitely until the connection times out on the server, and then moves on to wr.write(data) but this fails, of course, because the connection is now closed.
Does anyone know what the problem might be? I searched for issues regarding getOutputStream() on Android, but I did not find anything useful yet.
Thanks!
getOutputStream(). It doesn't throw an exception, it just hangs until the server times out the connection.