How can I make a simple HTTP request in MainActivity.java? (Android Studio)
You should not make network requests on the main thread. The delay is unpredictable and it could freeze the UI.
Android force this behaviour by throwing an exception if you use the HttpUrlConnection
object from the main thread.
You should then make your network request in the background, and then update the UI on the main thread. The AsyncTask
class can be very handy for this use case !
private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
URL url = new URL(urls[0]);
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;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
displayMessage(result);
}
}
And you start this process this way:
new GetUrlContentTask().execute(sUrl)