Android Series: GET, POST and Multipart POST requests

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 18-03-2010

11

Today I will describe shortly how to execute http GET and POST request on Android platform.
The code is very simple and straightforward, for post request with attachement, you would have to add apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your build path.

HTTP GET

try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}

HTTP POST

try {
        HttpClient client = new DefaultHttpClient();  
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user", "kris"));
            params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post);  
            HttpEntity resEntity = responsePOST.getEntity();  
            if (resEntity != null) {    
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }

HTTP POST with File attachment

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL);
     FileBody bin = new FileBody(file);
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
     reqEntity.addPart("myFile", bin);
     post.setEntity(reqEntity);  
     HttpResponse response = client.execute(post);  
     HttpEntity resEntity = response.getEntity();  
     if (resEntity != null) {    
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }
} catch (Exception e) {
    e.printStackTrace();
}

Hope this helps!

Android Series: Using GPS data

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 15-03-2010

1

In this tutorial i will show you how to quickly get the gps data using your android device version 1.6+.

All you have to do is to implement one interface and acquire LocationMangager from the adnroid system service.

public class LocationExampleAct extends Activity implements LocationListener{


    private double latitude;
    private double longitude;
    private LocationManager locMgr = null;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        locationTxt = (TextView)findViewById(R.id.location_id);
       
        locMgr = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
       
    }
   
    @Override
    public void onLocationChanged(Location location) {
        this.latitude = location.getLatitude();
        this.longitude = location.getLongitude();
        this.locationTxt.setText("Location: "+this.latitude +" : " + this.longitude);
        Log.i("Location change",""+latitude+ " : "+longitude) ;
    }
    @Override
    public void onProviderDisabled(String provider) {
       
    }
    @Override
    public void onProviderEnabled(String provider) {
       
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
       
    }
}

Android Series: Parsing JSON data with GSON

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 25-02-2010

7

Today I will describe how to parse json data using Gson open source library and how to convert it at the same time to java objects.
This is a typical cookbook example and should be very easy to follow.


1. Create an Android application with one activity, name it as you wish, if you are doing it in eclipse all the basic stuff will be generated for you which is exactly what we need.
2. Find an example url which responds in JSON, I have used Twitter Trends found here: http://search.twitter.com/trends.json
The example response looks like this:

{"as_of":"Thu, 25 Feb 2010 11:30:17 +0000","trends":[{"name":"#nowplaying","url":"http://search.twitter.com/search?q=%23nowplaying"},{"name":"#nothingworsethan","url":"http://search.twitter.com/search?q=%23nothingworsethan"},{"name":"Dubai Mall","url":"http://search.twitter.com/search?q=%22Dubai+Mall%22"},{"name":"iPad Gets","url":"http://search.twitter.com/search?q=%22iPad+Gets%22"},{"name":"#SuperJuniorTrot","url":"http://search.twitter.com/search?q=%23SuperJuniorTrot"},{"name":"Justin Bieber","url":"http://search.twitter.com/search?q=%22Justin+Bieber%22"},{"name":"Click","url":"http://search.twitter.com/search?q=Click"},{"name":"Jaebum","url":"http://search.twitter.com/search?q=Jaebum"},{"name":"#tosavemoney","url":"http://search.twitter.com/search?q=%23tosavemoney"},{"name":"Protection","url":"http://search.twitter.com/search?q=Protection"}]}



As you can see this json data contains date attribute called ‘as_of’ as well as array of items, each consisting of name and url attributes.
We will create two simple java classes wich will hold that information.
First one is TwitterTrends.java

package com.softwarepassion.jsonexample;

import java.util.Date;
import java.util.List;

public class TwitterTrends {

    private String as_of;
    private List<TwitterTrend> trends;
   
    public String getAs_of() {
        return as_of;
    }
    public void setAs_of(String asOf) {
        as_of = asOf;
    }
    public List<TwitterTrend> getTrends() {
        return trends;
    }
    public void setTrends(List<TwitterTrend> trends) {
        this.trends = trends;
    }
   
   
   
}

And the second one is a simple TwitterTrend.java

package com.softwarepassion.jsonexample;

public class TwitterTrend {
    private String name;
    private String url;
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}

TwitterTrends contains a list of TwitterTrend objects, both of them are simple beans and are very similar to the json response if you look closely :) .

Now the fun part begins.

Download the Gson library from http://code.google.com/p/google-gson/ and add it to your java build path in eclipse.
Once you do that, you can now transform your json response to Java object on Android Platform:
Get the response as InputStream:

public InputStream getJSONData(String url){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri);
            HttpResponse response = httpClient.execute(method);
            data = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        return data;
    }

Then use that input stream to create your java objects:

public void runJSONParser(){
        try{
        Log.i("MY INFO", "Json Parser started..");
        Gson gson = new Gson();
        Reader r = new InputStreamReader(getJSONData("http://search.twitter.com/trends.json"));
        Log.i("MY INFO", r.toString());
        TwitterTrends objs = gson.fromJson(r, TwitterTrends.class);
        Log.i("MY INFO", ""+objs.getTrends().size());
        for(TwitterTrend tr : objs.getTrends()){
            Log.i("TRENDS", tr.getName() + " - " + tr.getUrl());
        }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

Easy ha!

Apache Click on Google App Engine – Hello World Example

Posted by admin | Posted in Cloud Computing, General Programming | Posted on 19-02-2010

1

Hello World!
If this blog would run on App Engine and was build with Apache Click I could finish this tutorial right here :) .
But more seriously, I will describe short step by step tutorial on how to get started with Apache Click on Google App Engine.
I’m assuming that you have GAE plugin for eclipse installed already as well as the latest libraries for Apache Click downloaded somewhere on your machine. (If not look at my previous post on how to get started with Apache Click on Eclipse Galileo (here).

If all is set up, lets get started..


1. Add new GAE type ‘Web Application Project’ (the one with blue google icon)

2. Copy click-2.1.0.jar and click-extras-2.1.0.jar to the lib directory under war/WEB-INF/lib of your GAE project.

3. Click on the project and select ‘Properties’ when you will modify the ‘Java Build Path’.

When changing the build path, select the two libraries you have added to you lib folder in point 2.

4. Delete the auto-generated GAE project stuff, like servlet and index.html files.
5. Create new class called ‘Index’

package com.softwarepassion.clickgae;

import java.util.Date;
import org.apache.click.Page;

public class Index extends Page{
   
    private Date time = new Date();

    public Index() {
        addModel("time", time);
    }

}



Note the package you choose for you newly created class file, it will be needed when modifying config files later.

6. Create click.xml file in the same location where your web.xml file exists.
7. Modify your web.xml file to look similar to the one presented below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <listener>
         <listener-class>org.apache.click.extras.gae.GoogleAppEngineListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>ClickServlet</servlet-name>
    <servlet-class>org.apache.click.ClickServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ClickServlet</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>
</web-app>

It looks like ordinary web.xml file with one important addition: the listener section.

8. Add content to your click.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<click-app charset="UTF-8">
  <pages>
    <page path="index.htm" classname="com.softwarepassion.clickgae.Index"></page>
  </pages>
  <mode value="development"/>
</click-app>

9. Add index.htm file to the war directory

<html>
  <body>

    <h2>Hello World</h2>

    Hello world from Click at $time

  </body>
</html>

10. Deploy your app to Google App Engine and go to the url: http://yourappname.appspot.com

You should see very simple website with current time printed.