REST API with HTTP Authentication – Android & Beanstalk example

Featured Image

Hello everyone. For the last few months I have had a lot of work on my hands, thus ignoring my Android development skills. Lately however, seems like my appetite for mobile apps development is back. Or is it just my way of escaping the everyday struggle with large Magento database and sea of custom code. Anyhow, Android platform is a great exhaust valve for me.

There has been some talk about our company starting to use Beanstalk service (boss if you are reading this, I hope you get us Beanstalk account :)). Anyhow, one of the cool things I like about the Beanstalk is their REST API, more info here api.beanstalkapp.com.

This was more then enough for me to start poking with Android, HTTP Authentication, consuming REST service, etc.

Here is an example of REST API method call from Android that does the username/password authentication on the Beanstalk service. You can check this url for the detailed info on what the response returns.

package net.ajzele.beanstalk.stalkmanager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class HomeActivity extends Activity {
	String MY_APP_TAG = "net.ajzele.beanstalk.stalkmanager";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		/* START Test/Play with beanstalk API */
		String username = "brankoa";
		String host = "brankoa.beanstalkapp.com";
		String password = "MyPassHere";
		String urlBasePath = "http://" + username + ".beanstalkapp.com/api/";
		String urlApiCall_FindAllRepositories = urlBasePath
				+ "repositories.xml";
		try {
			HttpClient client = new DefaultHttpClient();
			AuthScope as = new AuthScope(host, 443);
			UsernamePasswordCredentials upc = new UsernamePasswordCredentials(
					username, password);
			((AbstractHttpClient) client).getCredentialsProvider()
					.setCredentials(as, upc);
			BasicHttpContext localContext = new BasicHttpContext();
			BasicScheme basicAuth = new BasicScheme();
			localContext.setAttribute("preemptive-auth", basicAuth);
			HttpHost targetHost = new HttpHost(host, 443, "https");
			HttpGet httpget = new HttpGet(urlApiCall_FindAllRepositories);
			httpget.setHeader("Content-Type", "application/xml");
			HttpResponse response = client.execute(targetHost, httpget,
					localContext);
			HttpEntity entity = response.getEntity();
			Object content = EntityUtils.toString(entity);
			Log.d(MY_APP_TAG, "OK: " + content.toString());
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(MY_APP_TAG, "Error: " + e.getMessage());
		}
		/* END Test/Play with beanstalk API */
	}
}

Important thing to keep an eye on are Beanstalk specific account information, like username, password, your account url. So, if you plan on copy-pasting the code, please set those accordingly.

Also, response is shown on the screenshot below.

Basically I think the example alone speaks for it self. No need to get too deep into explaining things.

Hope it helps someone.

6
Top

Care to rate this post?

Author

Branko Ajzele

Ex Inchooer

Worked at Inchoo as a Backend Developer/CTO from 2008 to 2013

Other posts from this author

Discussion 6 Comments

Add Comment
  1. Yes, yes… I am reading this. You are invited to “Stabljiku Graha” or Beanstalk. :)

  2. First of all thx for your code and realization at all, can i ask you for help. This apache packages can do GET or POST or DEL request? Can i realize it for my requests?

  3. https://api.connect2field.com/C2FDataSvc.svc/
    this is the api how can i pass this in android and done authentication in android

  4. Mario

    Thank you! You made my day! :)

  5. Rafiqul

    I got an error message when debugging in Eclipse

    “The target server failed to respond”

    at line HttpResponse response = client.execute(targetHost, httpget, localContext);

    The content of xml file is here

    AndroidPeople
    http://www.androidpeople.com

    iPhoneAppDeveloper
    http://www.iphone-app-developer.com

    I also gave username, password and xml file name.

    how do I solve this problem
    Please help!

  6. IMHO you should provide an example of using HttpURLConnection instead of Apache HTTP client since HTTP client is almost depreciated and not recommended for future use.

    http://android-developers.blogspot.se/2011/09/androids-http-clients.html

    Great tutorial, though.

Add Your Comment

Please wrap all source codes with [code][/code] tags.
Top