Skip to content Skip to sidebar Skip to footer

Android Json To Php Server And Back

Can anybody offer a solution to the above? For now, all i want to do is send a JSON request to my server (for example: {picture:jpg, color:green}), have the PHP access the database

Solution 1:

OK, i've got the PHP. The below retrieves POST ed data and returns the service

<?php$data = file_get_contents('php://input');
$json = json_decode($data);
$service = $json->{'service'};

print$service;

?>

and the Android Code:

in onCreate()

path = "http://example.com/process/json.php";

    HttpClientclient=newDefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout// Limit
    HttpResponse response;
    JSONObjectjson=newJSONObject();
    try {
        HttpPostpost=newHttpPost(path);
        json.put("service", "GOOGLE");
        Log.i("jason Object", json.toString());
        post.setHeader("json", json.toString());
        StringEntityse=newStringEntity(json.toString());
        se.setContentEncoding(newBasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        post.setEntity(se);
        response = client.execute(post);
        /* Checking response */if (response != null) {
            InputStreamin= response.getEntity().getContent(); // Get the// data in// the// entityStringa= convertStreamToString(in);
            Log.i("Read from Server", a);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

and where ever you want

privatestatic String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

Solution 2:

On the PHP side, all you need is the built-in json_decode, which will deserialize your json and return an object (or an associative array if you pass true as the second argument).

On the Android side, you'll probably use the HTTP Libraries to execute your HTTP request and process the response. (But someone who's actually developed for Android might correct me)

Post a Comment for "Android Json To Php Server And Back"