I'm using Android Studio, and I've spent a few hours trying to do a simple HTTP request in my MainActivity.java file, and tried multiple ways, and seen many web pages on the subject, yet cannot figure it out.
When I try OkHttp, I get a error about not being able to do it on the main thread. Now I'm trying to do it this way:
public static String getUrlContent(String sUrl) throws Exception {
URL url = new URL(sUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}
I put that method directly in MainActivity.java, and my click event executes it from another method that is also in MainActivity.java:
try {
String str = getUrlContent("https://example.com/WAN_IP.php");
displayMessage(str);
}
catch(Exception e){
displayMessage(e.getMessage());
}
But right now there is no crash, and I can tell there is an exception thrown on the line that starts "BufferedReader", but e.getMessage() is blank.
I'm brand new to Android Studio and java, so please be kind and help me with this very basic problem. Eventually I will need to do post requests to the server, and it seems that OkHttp is the best way to go, but I'm not finding the "Hello World" of OkHttp in Android Studio documented anywhere online.