Java REST Client with Basic Authentication

This Java Client can be used to invoke any RESTful endpoint by proving a baseURL, username and password.

import org.apache.commons.codec.binary.Base64;

import java.util.List;

public class RESTInvoker {
    private final String baseUrl;
    private final String username;
    private final String password;

    public RESTInvoker(String baseUrl, String username, String password) {
        this.baseUrl = baseUrl;
        this.username = username;
        this.password = password;

    public String getRESTResponse(String accountId){
       getDataFromServer("account/" + accountId);

    String getDataFromServer(String path) {
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(baseUrl + path);
            URLConnection urlConnection = setUsernamePassword(url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {

            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);

    private URLConnection setUsernamePassword(URL url) throws IOException {
        URLConnection urlConnection = url.openConnection();
        String authString = username + ":" + password;
        String authStringEnc = new String(Base64.encodeBase64(authString.getBytes()));
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        return urlConnection;

2 Comments on “Java REST Client with Basic Authentication

  1. hi what does the ‘path’ parameter meant to do?
    String getDataFromServer(String path)

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: