Android, Kotlin, Programming

HTTP GET using Volley

I was making an Android app using Android Studio (3.1.3) which sends a HTTP GET request. The code was very similar to this:

String serverURL = "http://192.168.0.150/main_light/switch";
URL url = new URL(serverURL);
HttpURLConnection connection = null;
try {
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
    //Do something with this InputStream
    // handle the response
    int status = connection.getResponseCode();
    // If response is not success
    if (status != 200) {
        throw new IOException("Post failed with error code " + status);
    }
} catch (Exception e) {
    Log.e(TAG,e.toString());
} finally {
     if(connection != null)
         connection.disconnect();
}

The request was never sent. I tried everything but I¬†just couldn’t make it work. However!

I found a solution using Volley (https://developer.android.com/training/volley/simple). This code is in Kotlin but as you can see it is very simple and mostly importantly it works!

val queue = Volley.newRequestQueue(this)
val url = "http://192.168.0.150/main_light/switch"
val stringRequest = StringRequest(Request.Method.GET, url, null, null)
queue.add(stringRequest)

Don’t forget to add these lines to the AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s