Hdelossantos.com

Quick and easy Android HTTP POST of JSON string

by Hanly on Dec.24, 2009, under Tutorials

There are several ways to send data across the internet to a server on the Android. I was recently working on a project and needed to send a JSON string to the server to add data to a database. Additionally in certain cases I wanted to receive data back from the server. The fastest and easiest way to do this was to use HTTP POST android library and capture the response from the server using a response handler. On the server side the response was simply generated by echoing a JSON string.

public ArrayList<String> getServerData() throws JSONException, ClientProtocolException, IOException {
	    ArrayList<String> stringData = new ArrayList<String>();
	    DefaultHttpClient httpClient = new DefaultHttpClient();
		ResponseHandler <String> resonseHandler = new BasicResponseHandler();
		HttpPost postMethod = new HttpPost(URL_TO_PHP_FILE_TO_HANDLE_POST);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("someKey", someData); //Data being sent to the server, which should produce a reply

		nameValuePairs.add(new BasicNameValuePair("jsonString", jsonObject.toString()));
		postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		String response = httpClientexecute(postMethod,resonseHandler);

		JSONObject jsonResponse = new JSONObject(response);

		JSONArray serverData1 = jsonResponse.getJSONArray("data1");
		JSONArray serverData2 = jsonResponse.getJSONArray("data2");
		for(int i = 0; i < serverData1.length() && i < serverData2.length(); i++) {
			//Do something with the data
		}

		return //the data;
   }

The code above shows the receipt of those two JSON encoded arrays. In my case I had to get a little creative with the server side code since I wanted to send two arrays encoded in JSON. However, the PHP library’s JSON encoding differs from that of Android so I had to encode the two arrays I needed to send using loops.

// Android expects to receive JSON arrays like so
{"array_name":[data, data1, data2], "array2_name":[data, data1, data2]}

The PHP code I wrote to format my arrays in a JSON format Android would understand is below.

// Create the JSON string
        while($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
            $data1[] = $row['data1'];
            $data2[] = $row['data2'];
        }

        mysql_close($handle);

        $json = '{"data1":[';

        for($i = 0; $i < sizeof($data1); $i++) {
            $json = $json . $data1[$i];

            if($i < sizeof($data1) - 1)
                $json = $json . ',';
        }

        $json = $json . '],"data2":[';

        for($i = 0; $i < sizeof($data2); $i++) {
            $json = $json . $data2[$i];

             if($i < sizeof($data2) - 1)
                $json = $json . ',';
        }

        $json = $json . ']}';

        // Send the client a JSON string with the result
        echo ($json);

Tags: , , , , , , , , , ,

Related posts

:, , , , , , , , , ,

2 Comments for this entry

  • julio

    hi! this example is great…
    so i want to ask you if you could post a complete example…i don’t understand some steps… thank you

  • fernie

    can you post full code to this example?

    also, there are some typos!
    Line 13: should be: httpClient.execute

    thank you.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...


Warning: fsockopen() [function.fsockopen]: unable to connect to twitter.com:80 (Connection reset by peer) in /home/lableupunn/hdelossantos.com/blog/wp-includes/class-snoopy.php on line 1142