Saturday, July 14, 2012

Android shorten URL implementation

In Android applications sometimes we see a need to shorten a url to make a link easier to share, tweet, or email to friends. This article provides a sample Android activity that demonstrates how android shorten URL implementation could be achieved using the Google URL shortener service.

The demo application (UrlShorten) takes a long url as input and produces shortened URL based on google service.

URL Shorten Example

We use a AsyncTask to prevent the UI from getting blocked.
private class ShortenUrlTask extends AsyncTask<String, Void, String> {
}

We use a HttpClient with connection timeout of 5 seconds and socket timeout of 10 seconds. This is necessary to prevent the HttpClient from blocking due to network connectivity issues.
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

HttpClient hc = new DefaultHttpClient(httpParameters);

We create a HttpPost request and package the long URL in a JSON object.
HttpPost request = new HttpPost(GOOGLE_URL);
request.setHeader("Content-type", "application/json");
request.setHeader("Accept", "application/json");

JSONObject obj = new JSONObject();
obj.put("longUrl", mLongUrl);
request.setEntity(new StringEntity(obj.toString(), "UTF-8"));

Finally the HTTP post request is executed and the response is decoded as a string.
HttpResponse response = hc.execute(request);
if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.getEntity().writeTo(out);
    out.close();              
    return out.toString();
}

The string received is also JSON string. In onPostExecute we decode the response string and extract the "id" parameter which contains the shorted URL.
final JSONObject json = new JSONObject(result);
final String id = json.getString("id");

The Activity:-
package com.sourcetricks.com;

import java.io.ByteArrayOutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UrlShortenActivity extends Activity {

 private EditText mInputUrl = null;
 private TextView mOutput = null;
 private static Context mContext = null;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  mInputUrl = (EditText) findViewById(R.id.urlEditor);
  mOutput = (TextView) findViewById(R.id.tvOutput);
  mContext = this;

  Button btShorten = (Button) findViewById(R.id.btShorten);
  btShorten.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View arg0) {
    mOutput.setText("");
    ShortenUrlTask task = new ShortenUrlTask();
    task.execute(mInputUrl.getText().toString());
   }         
  });
 }

 // Async task to shorten url
 private class ShortenUrlTask extends AsyncTask<String, Void, String> {

  private final String GOOGLE_URL = "https://www.googleapis.com/urlshortener/v1/url";
  private String mLongUrl = null;

  @Override
  protected String doInBackground(String... arg) { 

   mLongUrl = arg[0];

   try {       
    // Set connection timeout to 5 secs and socket timeout to 10 secs
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 5000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 10000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    HttpClient hc = new DefaultHttpClient(httpParameters);

    HttpPost request = new HttpPost(GOOGLE_URL);
    request.setHeader("Content-type", "application/json");
    request.setHeader("Accept", "application/json");

    JSONObject obj = new JSONObject();
    obj.put("longUrl", mLongUrl);
    request.setEntity(new StringEntity(obj.toString(), "UTF-8"));

    HttpResponse response = hc.execute(request);

    if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
    {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     response.getEntity().writeTo(out);
     out.close();              
     return out.toString();
    }
    else {
     return null;
    }
   }
   catch ( Exception e ) {
    e.printStackTrace();        
   }  

   return null;
  }

  @Override
  protected void onPostExecute(String result) { 

   if ( result == null )
    return;   

   try {
    final JSONObject json = new JSONObject(result);
    final String id = json.getString("id");
    if ( json.has("id") ) { 
     ((Activity) mContext).runOnUiThread(new Runnable() {
      public void run() {
       mOutput.setText(id);   
      }
     });
    }
   }
   catch (JSONException e) {   
    e.printStackTrace();
   }
  }
 }
}

The complete project can be downloaded from here.

urlshorten

6 comments :

  1. Nice, it works!!! thanks for that

    ReplyDelete
  2. Plz explain why it is returning null at response.getStatusLine().getStatusCode() == HttpStatus.SC_OK

    ReplyDelete
  3. Hii..where do i run this project?

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top