I'm trying to establish a https connection between an android app (client) an my laptop (server). My https server is running as python script (with a letsencrypt certificate) which works fine as long as I try to connect it with chrome or another python script.
Now I wanted to implement the client in my android app. Therefore I added the permission to the AndroidManifest.xml
:
<uses-permission android:name="android.permission.INTERNET"/>
and added following lines to my MainActivity.java
(based on HttpURLConnection Reference on Android Developers!:
public void onButtonClicked(String message) {
try {
URL url = new URL("https://foo.bar.com/");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
mSecondFragment.updateMessage(message);
}
At the moment I just want to establish a connection to my https server and send a simple GET request without receiving any data. But my goal would be to parse an additional key value pair together with the GET
request that will be processed by the server:
"https://foo.bar.com?a=1"
I tried to keep it as simple as possible (that's the reason why I wanted to use java.net.HttpURLConnection
) but I assume the problem is not as trivial as I expected.
Maybe someone ran into the same problem and can help my with that :)
EDIT (Thanks to @atomicrat2552 and @petey):
I added an additional class that handles the request as an AsyncTask:
public class NetworkConnection extends AsyncTask<String, Void, NetworkConnection.Result> {
static class Result {
public String mResultValue;
public Exception mException;
public Result(String resultValue) {
mResultValue = resultValue;
}
public Result(Exception exception){
mException = exception;
}
}
protected NetworkConnection.Result doInBackground(String... urls) {
Result result = null;
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.connect();
result = new Result("Done");
}catch(Exception e) {
result = new Result(e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result;
}
}
This leads to a simplified onButtonClick method in MainActivity.java
:
NetworkConnection nwConn = new NetworkConnection();
public void onButtonClicked(String message) {
nwConn.execute("https://foo.bar.com");
mSecondFragment.updateMessage(message);
}
Again I tried to simplify the code in order to get a small working code a can extend later. The app doesn't crash anymore but my server still doesn't show any requests. If I'm using the browser on my phone everything works just fine. Any idea?