Using JSON in PHP

4

I am using json-simple from Java to receive and request data in JSON format from PHP. But I do not give with the way to do the correct code from PHP to send and receive and in Java to receive.

JAVA code to send and receive

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class JSONManager<T> {

    // CLASS PROPERTIES

    private static JSONManager ourInstance = new JSONManager();

    private static final String USER_AGENT = "Mozilla/5.0";
    private static final String SERVER_PATH = "http://localhost/";

    // CLASS METHODS

    public static JSONManager getInstance() {
        return ourInstance;
    }

    // CONSTRUCTORS

    private JSONManager() {
    }

    // METHODS

    public synchronized void send() throws IOException{

        // SE AÑADEN ALGUNOS DATOS...

        final JSONObject jsonObject = new JSONObject();

        jsonObject.put("name","foo");
        jsonObject.put("age", 20);

        final List listOfJSONObjects = new LinkedList<>(Arrays.asList(jsonObject));

        // SE GENERA EL STRING DE JSON...

        String jsonString = JSONValue.toJSONString(listOfJSONObjects);

        // SE MUESTRA POR CONSOLA EL JSON GENERADO...

        System.out.printf("JSON generado: %s \n\n", jsonString);

        // SE CODIFICA EL JSON A UNA URL

        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        String urlString = SERVER_PATH+"onListenerJSONJava.php"; // TODO <-- No se cómo debe ser el código allí.

        // SE GENERA UNA URL Y SE ABRE LA CONEXIÓN CON EL SERVIDOR

        final HttpURLConnection huc = (HttpURLConnection) new URL(urlString).openConnection();

        // SE AÑADE LA CABECERA

        huc.setRequestMethod("POST");
        huc.setRequestProperty("User-Agent", USER_AGENT);
        huc.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // SE ENVIAN LOS DATOS

        final String postParameters = "jsonJAVA="+jsonString;

        huc.setDoOutput(true);
        final DataOutputStream dos = new DataOutputStream(huc.getOutputStream());
        dos.writeBytes(postParameters);
        dos.flush();
        dos.close();

        // SE CAPTURA LA RESPUESTA DEL SERVIDOR

        final int responseCode = huc.getResponseCode(); // TODO <-- No se cómo debe ser el código allí.

        BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }

        // SE MUESTRA POR CONSOLA EL 'MENSAJE' ENVÍADO AL SERVIDOR Y SU CÓDIGO DE RESPUESTA

        System.out.printf("\nSending 'POST' request to URL: %s\nPost parameters: %s\nResponse code: %d\n",
                urlString, postParameters,responseCode);

        // SE MUESTRA LA RESPUESTA DEL SERVIDOR Y SE CIERRA LA CONEXIÓN

        System.out.printf("\nResponse: %s:",response.toString());
        br.close();
    }

    public <T extends Object> T receive() {
        // TODO <-- No sé hacerlo aquí.
        return null;
    }

}

PHP code to receive. // Fala send ...

    

    if(isset($_POST["jsonJAVA"])){

        $json = $_POST["jsonJAVA"];

        // EN ESTE PUNTO NO SÉ COMO OBTENER EL JSON DESDE MI APP EN JAVA Y RESPONDER POR SUPUESTO...

            // TODO

        // GUARDAR DATOS EN BBDD SI ES NECESARIO TRAS VALIDARLOS...

            // TODO <-- Esto ya sé hacerlo.
    }

?>
    
asked by dddenis 02.02.2016 в 23:40
source

3 answers

4

With the Java part I can help you.

To send data to the server, obviously we will use the POST method, now; What I do not like about the approach you are taking is the way you create the JSON. Java is an object-oriented language and therefore the problems should be treated in that way, I propose the following:

Suppose I want to send a JSON of type Person, a person has first and last name attributes; then I create a Person object like this:

public class Persona {
    private String nombre;
    private String apellido;

    //incluir los metodos get y set para cada atributo
}

Then somewhere in my code, I must populate the frame I want to send to the server, either by database or with static data

 Persona p = new Persona();
 p.setNombre("Yo");
 p.setApellido("Tu");

To convert this class into a JSON on the fly I recommend this what I did using Gson

private static Gson gson = new Gson();

public static String objetoAJson(Object o) {
    return gson.toJson(o);
}

That way you only pass the object (List or Unique Object) to the objetoAJson method and a String will be returned with your JSON ready to send.

Now, after you have the JSON ready, you should send it with a POST

I propose this method to you

public static String sendPost(String url, String data) throws Exception {

        HttpURLConnection  con = (HttpURLConnection) new URL(url).openConnection();

        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept","*/*");
        con.setRequestProperty("Content-Type","application/json");

        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(data);
        wr.flush();
        wr.close();
        data = null;

        System.out.println("\nSending 'POST' request to URL : " + url);

        InputStream it = con.getInputStream();
        InputStreamReader inputs = new InputStreamReader(it);

        BufferedReader in = new BufferedReader(inputs);
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        System.out.println("Servidor dice : " + response.toString());
        return response.toString();
    }

You should only define the URL where the content should arrive, and of course; the content (JSON) that you are going to send. The rest depends on your code in the server that is in PHP and there if I do not know why I avoid PHP.

To receive JSON from your server, we use GET (even simpler)

public static InputStream getJson(String _url) {
        try{
            URL url = new URL(_url);
            URLConnection urlConnection = url.openConnection();
            return urlConnection.getInputStream();
        }catch(Exception e) {
            return null;
        }
}

The result will be returned in an InputStream that can be transformed to String like this:

String text = new Scanner(>>aquí tu stream recibido<<).useDelimiter("\A").next();

And that's it, you'll have the server's response (JSON or some error) and you'll be able to work with it.

Any questions, to order. Regards!

    
answered by 04.02.2016 / 18:32
source
2

As far as I understand, you are making a request XHR from Java to PHP , in which the content of the request is a JSON . If so, in your file PHP the way to interpret it would be using json_decode () .

<?php

    if(isset($_POST["jsonJAVA"])){
        $json = json_decode($_POST["jsonJAVA"]);

        # De aquí en adelante es validar, guardar en DB 
        # y responder

    }
    
answered by 03.02.2016 в 14:45
0

PHP must return some type of HTML data. PHP is executed on the server side and the JAVA request is made on the client side, so you have to write some HTML type data, as if you were visiting a web page. Let me explain with your example:

<?php
    // Comprobacion
    if(isset($_POST["jsonJAVA"])){
        // Ejecutas todo el contenido que quieras hacer con esta
        // variable, ya sea guardar o sacar datos.
        // Si quisieras sacar valores a datos json seria:
        $json['nombre_salida'][] = array('variable' => 'dato', 'variable' => 'dato'); //Etc
    }
    // Finalmente necesitamos establecer las cabeceras y sacar los datos a HTML
    header('Content-Type: application/json');
    header('Content-Type: text/html; charset=utf-8');
    echo json_encode($json);
?>

That would be the syntax. Greetings.

    
answered by 03.02.2016 в 18:02