Android: Simple HttpClient to send/receive JSON Objects

This tutorial is focused on creating a very simple HTTP client for Google's mobile operating system Android, which then can communicate with a web server and exchange JSON information. I won't go too much into detail, since the code is pretty much self-explaining and already has a lot of comments describing the program flow.


1) Create a new Android project

2) Add permission to access the Internet from your application to your AndroidManifest.xml

    
    


3) Create a new (static) class called HttpClient.java


4) Add the following code to your MainActivity.java


The full source code is also available on GitHub for download.

Check the official Android documentation for more information about JSONObjects and Apache's HttpClient classes.

I hope this tutorial was helpful for you. If it was too simple for your needs stay tuned. Upcoming tutorials will deal with the following topics:
  • Creating a separate HttpClient thread to uncouple the hard work happening in the background from the user interface
  • Dealing with HTTP exceptions: transport exceptions, protocol exceptions, timeouts.
  • Setting up a BackgroundService and a ServiceInterface, which will be the new home for our HttpClient. This enables many activies to simply connect to the service and to access the resources provided instead of creating a new HttpClient object for each activity
  • Instead of using a simple HttpClient (as shown in this tutorial), we will utilize ClientConnectionManager to provide us with a connection pool to save resources and improve performance




I've just launched a new side project of mine:

Bugfender - A modern remote logger tailor-made for mobile development

It's currently free and you can sign up here: https://app.bugfender.com/signup

Any kind of feedback is more than appreciated :-)

7 comments:

  1. extremely helpful

    ReplyDelete
  2. Very Helpful. I am new to android and java. I just had one doubt. Where in the code here did you specify the URL? And how does the code give no errors without it?

    ReplyDelete
  3. very helpful, thanks a lot

    ReplyDelete
  4. What does the php-script receive? Is it:

    {
    "json":"meddelande",
    "header": {
    "deviceVersion":"2.0",
    "devicrType":"Android",
    "language":"es-es"
    }
    } ?

    ReplyDelete
  5. Hi,
    I have post json data but responce msg is " your json obect contain special characters , please help

    ReplyDelete