Sunday, September 11, 2011

Android Programming - Url Connect

This the basis for web service. Android + Web Service is a future will be for me. With open platform you can access open information. That's really great I think.
Simple, with a piece of code to access web service in Android, but remember, this is basic implementation, you need add more functionality for sure, like checking internet connection, handling the error and encoding the output (XML or JSON).
This is my code, simple, as a function that you can called anywhere in your program.
public String connect(String url) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
             sb.append(line);
        }
        return sb.toString();
    }

You need an input with type string that contained the url of the web services, the code then connect and copy the output as a string too.
For more advanced usage you can directly encoded the output string to format that you need. :)

Categories: , , , , , ,

0 komentar:

Copyright © Johannes Dwi Cahyo | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com | BTheme.net      Up ↑