Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

send a json object to a server

android json

  • Please log in to reply
1 reply to this topic

#1 lintwurm

lintwurm

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 261 posts
  • Programming Language:C, Java, C++, C#, PHP, (Visual) Basic, Python, Visual Basic .NET

Posted 13 March 2011 - 08:14 AM

Hello all,

I've been having a couple of problems coding this android application. What I want it to do is send a json object to a server. I have some code, was just wondering if someone can help me and tell me where I have gone wrong?

First is the JSON.java File:
package example.JSON;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class JSON extends Activity
{
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
		JSONObject json = new JSONObject();
		try
		{
			json.put("Longtude", "15");
			json.put("Lattetude", "30");
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = "http://www.upgardens.co.za/upload.php";
		HttpResponse re;
		String temp = new String();
		try
		{
			re = HTTPPoster.doPost(url, json);
			temp = EntityUtils.toString(re.getEntity());
		}
		catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (temp.compareTo("SUCCESS")==0)
		{
		    Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();
		}
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main);
    }
}

Now HTTPPoster.java
package example.JSON;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

public class HTTPPoster
{
	public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
	{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost request = new HttpPost(url);
	    HttpEntity entity;
	    StringEntity s = new StringEntity(c.toString());
	    s.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
	    entity = s;
	    request.setEntity(entity);
	    HttpResponse response;
	    response = httpclient.execute(request);
	    return response;
	}
}

and now the php script on the server
upload.php
<?php
 
	// decode JSON string to PHP object
	$decoded = json_decode($_GET['json']);
	// do something with data here
	$Longitude = $decoded['Longitude'];
	$Lattetude = $decoded['Lattetude'];
	$myFile = "testFile.txt";
	$fh = fopen($myFile, 'w') or die("can't open file");
	$stringData = $Longitude;
	fwrite($fh, $stringData);
	$stringData = $Lattetude;
	fwrite($fh, $stringData);
	fclose($fh);
	// create response object
	$json = array();
	$json['errorsNum'] = 2;
	$json['error'] = array();
	$json['error'][] = 'Wrong Longtude!';
	$json['error'][] = 'Wrong Lattetude!';
	// encode array $json to JSON string
	$encoded = json_encode($json);
	// send response back to index.html
	// and end script execution
	die($encoded);
?>


I should also say in the first code segment where I call: re = HTTPPoster.doPost(url, json);
is where the problem is...
The class I created is doing something funky...


Thanks upfront for any help

Edited by Roger, 23 July 2011 - 02:43 PM.
added prefix

  • 1

#2 Parabola

Parabola

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 221 posts

Posted 27 July 2011 - 09:24 AM

I have a suggestion. Don't do a json object for only 2 variables... do a request, or a post. if anything, use php, and send it a url such as
<url>/<name>.php?long=<longitude>&lat=<latitude>

If you absolutely have to use json object upstream, maybe you can reverse my code somehow
here is a sample of a request i do to get info from a mySql server via php and json:
Note the use of nameValuePairs
String result = new String();            result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("device",product));
            InputStream is = null;
            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("<link removed>");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                
            }catch (Exception e)
            {
                
                Log.e("log_tag", "Error in http connection "+e.toString());
            }
            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                
                result = sb.toString();
                
            }catch (Exception e) {
                Log.e("log_tag", "Error converting result "+e.toString());
            }
            
            try{
                if(result != null){
                JSONArray jArray = new JSONArray(result);
                Log.i("log_tag", Integer.toString(jArray.length()));
                for(int i=0;i<jArray.length(); i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    
                        sitems.add(json_data.getString("kernel_name") + " " + json_data.getString("kernel_version"));
                        fitems.add(json_data.getString("download_url"));
                }}
                else{
                    Toast.makeText(getApplicationContext(), "NULL", Toast.LENGTH_SHORT).show();
                }
                
            }catch(JSONException e)
            {
                Log.e("log_tag", "Error parsing data "+e.toString());
                
            }

  • 1
Programmer (n): An organism that can turn caffeine into code.
Programming would be so much easier without all the users.





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download