I am using json-simple from Java to receive and request data in JSON format from PHP. But I can't figure out how 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. // Fail to 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.
}
?>
With the Java part I can help you.
To send data to the server, we are obviously going to use the POST method now; what I don't like about the approach you're taking is the way you create the JSON. Java is an object-oriented language and therefore problems should be treated that way, I propose the following:
Suppose I want to send a JSON of type Person, a person has first and last name attributes; so I create a Person object like this:
Then somewhere in my code, I have to populate the frame that I want to send to the server, either by database or with static data
To convert this class into a JSON on the fly I recommend this that I did using Gson
That way you only pass the object (List or Single Object) to the method
objetoAJson
and a will be returnedString
with your JSON ready to send.Now, after you have the JSON ready, you need to send it with a POST
I propose this method
You only have to 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 on the server that is in PHP and there I really don't know why I avoid PHP.
To receive JSON from your server, we use GET (easier still)
The result will be returned in an InputStream that can be transformed to a String like so:
And that's it, you'll have the response from the server (JSON or some error) and you'll be able to work with it.
Any doubt as to the order. Cheers!
As far as I understand, you are making a request
XHR
from Java toPHP
, in which the content of the request is aJSON
. If so, in your filePHP
the way to interpret would be using json_decode() .The PHP must return some type of HTML data. PHP is executed on the server side and the JAVA request is done 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:
That would be the syntax. Greetings.