Http Get using Android HttpURLConnection

Http Get using Android HttpURLConnection

To perform an HTTP GET request using HttpURLConnection in an Android application, you can follow these steps. Make sure you handle network operations in a background thread to avoid blocking the main UI thread.

Here's an example of how to perform an HTTP GET request using HttpURLConnection:

import android.os.AsyncTask; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetRequest extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String result = ""; HttpURLConnection urlConnection = null; try { // Create a URL object with the provided URL URL url = new URL(urls[0]); // Open a connection to the URL urlConnection = (HttpURLConnection) url.openConnection(); // Set the request method to GET urlConnection.setRequestMethod("GET"); // Connect to the server urlConnection.connect(); // Check if the response code is OK (HTTP 200) int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Read the response from the server InputStream inputStream = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { result += line; } } else { result = "HTTP GET request failed with response code: " + responseCode; } } catch (IOException e) { e.printStackTrace(); result = "Error: " + e.getMessage(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return result; } @Override protected void onPostExecute(String result) { // Handle the HTTP GET response in the UI thread Log.d("HttpGetRequest", "Response: " + result); // You can update UI components or perform other actions here } } 

To use this HttpGetRequest class in your Android application, you can execute it from an activity or fragment like this:

new HttpGetRequest().execute("https://example.com/api/data"); // Replace with your API endpoint 

This code will initiate an asynchronous HTTP GET request, fetch the response, and log it in the onPostExecute method. You can replace the URL with your desired API endpoint and handle the response according to your application's requirements.


More Tags

topshelf rabbitmq-exchange persistent-storage mysql-error-1222 svg-android quote javascript-intellisense project-reference subclassing client

More Java Questions

More Everyday Utility Calculators

More Auto Calculators

More Mortgage and Real Estate Calculators

More Stoichiometry Calculators