Android HttpURLConection - Top HTTP POST Examples


Android HttpURLConnection HTTP POST Tutorial.

This section contains various examples that allow you make HTTP POST request against a server. We use android's standard networking class HttpURLConection to make our requests.

Quick HttpURLConnection HowTo Examples

Let's start by looking at some HowTo examples.

1. How to make a HttpURLConection HTTP POST Request and Return a response

Let's say we we provide you with a URL encoded string data. You are supposed to send them via a HTTP POST Request using HttpURLConnection.

Here's how we can do it.

    public static JSONObject post(String url_string, String encoded_data) throws IOException {
        URL url;
        StringBuilder sb = null;
        String data;

            url = new URL(url_string);
            HttpURLConnection connection = null;

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
            wr.write(encoded_data);
            wr.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            wr.close();
            br.close();

        JSONObject response = null;
        try {
            response = new JSONObject(sb.toString());
        } catch (JSONException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return response;
    }

2. How to make a HttpURLConection HTTP POST Request with Authentication

We want to make this post request in a background thread using AsyncTask class. We make that POST Request and receive a result.

Say for instance we want to make the POST request to GitHub.

Our first step would be to create a class that would then represent our result, lets call the class HTTPConnectionResult.

Our result will contain a string and a response code.

public class HTTPConnectionResult {
    private final String result;
    private final int responceCode;

    public HTTPConnectionResult(String result, int responceCode) {
        this.result = result;
        this.responceCode = responceCode;
    }

    public String getResult() {
        return result;
    }

    public int getResponceCode() {
        return responceCode;
    }
}

Then let's another class to represent User session data. This class will store data associated with a given user session, or the time the request was being made.

Those data for us will comprise the id, credentials, token and login.

public class UserSessionData {

    private final String id;
    private final String credentials;
    private final String token;
    private final String login;

    public UserSessionData(String id, String credentials, String token, String login) {
        this.id = id;
        this.credentials = credentials;
        this.token = token;
        this.login = login;
    }

    public static UserSessionData createUserSessionDataFromString(String data) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        String[] array = data.split(";");
        return new UserSessionData(array[0], array[1], array[2], array[3]);
    }

    public String getLogin() {
        return login;
    }

    public String getId() {
        return id;
    }

    public String getCredentials() {
        return credentials;
    }

    public String getToken() {
        return token;
    }

    @Override
    public String toString() {
        return id + ";" + credentials + ";" + token + ";" + login;
    }
}

What about a last class before looking at our AsyncTask, in this case a Util class:

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

public final class Utils {
    public static final String SHARED_PREF_NAME = "com.ok.lab.GitJourney";
    public static final String DMY_DATE_FORMAT_PATTERN = "dd-MM-yyyy";
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private Utils() {

    }

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        Log.e("TAG", "verifyStoragePermissions");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    public static DateFormat createDateFormatterWithTimeZone(Context context, String pattern) {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        boolean timeZone = sharedPref.getBoolean("timezone_switch", true);
        SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.getDefault());
        if (timeZone) {
            formatter.setTimeZone(TimeZone.getDefault());
        } else {
            String customTimeZone = sharedPref.getString("timezone_list", TimeZone.getDefault().getID());
            formatter.setTimeZone(TimeZone.getTimeZone(customTimeZone));
        }
        return formatter;
    }

    public static String getStackTrace(Exception e) {
        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        e.printStackTrace(printer);
        printer.close();
        return writer.toString();
    }
}

Then now we come tou our AsynTask class.

Here's the thing, this class will perform an authentication to our Github account for instance. We will make a HTTP POST request for this and receive a result.

We have to do this in a background thread to avoid freezing the user interface.

The request itself we perform it in the doInBackground method. The result of this method will be our UserSessionData object.

Then when the results are back they will automatically get passed to our onPostExecute() method.

From there we can receive those data and store them in SharedPreferences. This allows our app to remember login details.

Here's the code for that.

public class AuthenticationAsyncTask extends AsyncTask<String, Integer, UserSessionData> {

    private static final String TAG = AuthenticationAsyncTask.class.getSimpleName();
    private final Context context;

    public AuthenticationAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected UserSessionData doInBackground(String... args) {
        try {
            HttpURLConnection connect = (HttpURLConnection) new URL(context.getString(R.string.url_connect)).openConnection();
            connect.setRequestMethod("POST");
            connect.setDoOutput(true);
            String inputString = args[0] + ":" + args[1];
            String credentials = Base64.encodeToString(inputString.getBytes(), Base64.NO_WRAP);
            String authentication = "basic " + credentials;
            connect.setRequestProperty("Authorization", authentication);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("client_id", context.getString(R.string.client_id));
            jsonObject.put("client_secret", context.getString(R.string.client_secret));
            jsonObject.put("note", context.getString(R.string.note));
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("repo");
            jsonArray.put("user");
            jsonObject.put("scopes", jsonArray);

            OutputStream outputStream = connect.getOutputStream();
            Log.v(TAG, "request body = " + jsonObject.toString());
            outputStream.write(jsonObject.toString().getBytes());
            connect.connect();
            int responseCode = connect.getResponseCode();

            Log.v(TAG, "responseCode = " + responseCode);
            if (responseCode != HttpURLConnection.HTTP_CREATED) {
                return null;
            }
            InputStream inputStream = connect.getInputStream();
            String response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            Log.v(TAG, "response = " + response);
            JSONObject jObj = new JSONObject(response);

            HttpURLConnection reconnect = (HttpURLConnection) new URL(context.getString(R.string.url_login_data)).openConnection();
            reconnect.setRequestMethod("GET");

            authentication = "token " + jObj.getString("token");
            reconnect.setRequestProperty("Authorization", authentication);

            reconnect.connect();
            responseCode = connect.getResponseCode();
            Log.v(TAG, "responseCode = " + responseCode);

            inputStream = reconnect.getInputStream();
            response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            Log.v(TAG, "response = " + response);
            JSONObject object = new JSONObject(response);
            UserSessionData data = new UserSessionData(jObj.getString("id"), credentials, jObj.getString("token"), object.getString("login"));
            return data;
        } catch (Exception e) {
            Log.e(TAG, "Login failed", e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(UserSessionData userSessionData) {
        super.onPostExecute(userSessionData);
        if (userSessionData != null) {
            SharedPreferences prefs = context.getSharedPreferences(Utils.SHARED_PREF_NAME, 0);
            SharedPreferences.Editor e = prefs.edit();
            e.putString("userSessionData", userSessionData.toString()); // save "value" to the SharedPreferences
            e.apply();
            Intent intent = new Intent(context, MainActivity.class);
            context.startActivity(intent);
        } else {
            Toast.makeText(context, context.getString(R.string.login_failed), LENGTH_SHORT).show();
        }
    }
}

NB/= This is not a standalone example, and is meant to be incorporated into your own project.

2. How to make a HTTP GET Request

We've seen how to make a HTTP POST request, in the first part. Let's now continue and create another async task class that will this time perform a HTTP GET request.

Let's now say we want to download a GitHub Readme.

But first we have to establishe a connection for making a HTTP GET request.

We just use the openConnection() method of the URL class and make sure to our request method as GET:

            HttpURLConnection connect = (HttpURLConnection) new URL(uri).openConnection();
            connect.setRequestMethod("GET");

Then we get our authentication token from our SharedPreferences and set it as the request property, with the key being Authorization while the value being that token:

            String authentication = "token " + currentSessionData.getToken();
            connect.setRequestProperty("Authorization", authentication);

Then connect.

public class FetchHTTPConnectionService {
    private static final String TAG = FetchHTTPConnectionService.class.getSimpleName();
    private final String uri;
    private final UserSessionData currentSessionData;

    public FetchHTTPConnectionService(String uri, UserSessionData currentSessionData) {
        this.uri = uri;
        this.currentSessionData = currentSessionData;
    }

    public FetchHTTPConnectionService(String uri, Context context) {
        this.uri = uri;
        SharedPreferences prefs = context.getSharedPreferences(Utils.SHARED_PREF_NAME, 0);
        String sessionDataStr = prefs.getString("userSessionData", null);
        currentSessionData = UserSessionData.createUserSessionDataFromString(sessionDataStr);
    }

    public HTTPConnectionResult establishConnection() {
        try {
            HttpURLConnection connect = (HttpURLConnection) new URL(uri).openConnection();
            connect.setRequestMethod("GET");

            String authentication = "token " + currentSessionData.getToken();
            connect.setRequestProperty("Authorization", authentication);

            connect.connect();
            int responseCode = connect.getResponseCode();

            Log.v(TAG, "responseCode = " + responseCode);
            InputStream inputStream = connect.getInputStream();
            Log.v(TAG, "inputStream " + inputStream);
            String response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            Log.v(TAG, "response = " + response);
            return new HTTPConnectionResult(response, responseCode);

        } catch (Exception e) {
            Log.e(TAG, "Get data failed", e);
            return null;
        }
    }
}

The actual download, we said, will have to be performed in a background thread. This allows the UI to remain responsive.

Here's the code:

public class RepoReadmeDownloadAsyncTask extends AsyncTask<String, Void, String> {

    private static final String TAG = RepoReadmeDownloadAsyncTask.class.getSimpleName();
    private final Context context;
    private final OnRepoReadmeContentLoadedListener listener;
    private UserSessionData currentSessionData;

    public RepoReadmeDownloadAsyncTask(Context context, OnRepoReadmeContentLoadedListener listener) {
        this.context = context;
        this.listener = listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        SharedPreferences prefs = context.getSharedPreferences(Utils.SHARED_PREF_NAME, 0);
        String sessionDataStr = prefs.getString("userSessionData", null);
        currentSessionData = UserSessionData.createUserSessionDataFromString(sessionDataStr);
    }

    @Override
    protected String doInBackground(String... args) {
        String repo = args[0];
        String login = args[1];
        try {
            HttpURLConnection connect = (HttpURLConnection) new URL(context.getString(R.string.url_repo_readme, login, repo)).openConnection();
            connect.setRequestMethod("GET");

            String authentication = "basic " + currentSessionData.getCredentials();
            connect.setRequestProperty("Authorization", authentication);
            connect.connect();
            int responseCode = connect.getResponseCode();

            Log.v(TAG, "responseCode = " + responseCode);
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return null;
            }
            InputStream inputStream = connect.getInputStream();
            String response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            Log.v(TAG, "response = " + response);
            JSONObject jsonObj = new JSONObject(response);
            String downloadUrl = jsonObj.getString("download_url");
            FetchHTTPConnectionService fetchHTTPConnectionService = new FetchHTTPConnectionService(downloadUrl, context);
            HTTPConnectionResult result = fetchHTTPConnectionService.establishConnection();
            Log.v(TAG, "responseCode = " + result.getResponceCode());
            Log.v(TAG, "result = " + result.getResult());
            return result.getResult();
        } catch (IOException | JSONException e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    @Override
    protected void onPostExecute(String content) {
        super.onPostExecute(content);
        listener.onRepoContentLoaded(content);
    }

    public interface OnRepoReadmeContentLoadedListener {
        void onRepoContentLoaded(String content);
    }
}

HttpURLConnection HTTP POST Examples

Let's look at some examples.

Android MySQL Insert tutorial.In this tutorial,we look at Android MySQL database,saving data to MySQL. We insert data from edittexts into mysql.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post