What my code is about is a connection and sending information to a database, in this case I created one CRUD
to make things easier, also that was one of the requirements...
For now my CRUD
works correctly, there is no problem, except in the case that I try to use tildes to send information to a file .php
, I have 4 basic files which represent the CRUD
:
- create.php
- update.php
- read.php
- delete.php
While their names are pretty irrelevant at the moment, I'm puzzled by the fact that whatever I do on the backend specifically in the update.php file , the data I get back isn't in the , it UTF-8
seems to arrive as unicode + UTF-8
or some other format, whatever you do...
I suspect it's about what I use to encode the parameters of the URL
, use URLEncoder
.
According to the update.php file , when sending the parameters, one of them is received with the following format in the variable POST
:
"data":{":plan":"Habitaci\u00f3n ejecutiva",":email":"[email protected]"}
What you should receive on the backend is:
"data":{":plan":"Habitación ejecutiva",":email":"[email protected]"}
That is the representation of how the data arrives at the backend and the expected result, therefore it is not literally what is obtained in the backend (the format of array and associative array is used in the POST variable to access that data in a way quiet).
For some reason, when executing the query update
, it fails when the query has accents, so it occurred to me that the problem of the query not executing successfully also has to do with the encoding, when it does not have accents it works.
This is the frontend code that makes the connection and handles the operations CRUD
:
package hotelh_m;
import com.google.gson.JsonElement;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class CRUD {
public static final String serverURL = "http://localhost/hotelH_M/";
public static final String createURL = CRUD.serverURL + "create.php";
public static final String readURL = CRUD.serverURL + "read.php";
public static final String updateURL = CRUD.serverURL + "update.php";
public static final String deleteURL = CRUD.serverURL + "delete.php";
public static String currentOperationURL = CRUD.readURL;
private static int currentTable = 0;
CRUD(){
}
private static void setCurrentOperation(String operation){
switch(operation.toLowerCase()){
case "create":
CRUD.currentOperationURL = CRUD.createURL;
break;
case "read":
CRUD.currentOperationURL = CRUD.readURL;
break;
case "update":
CRUD.currentOperationURL = CRUD.updateURL;
break;
case "delete":
CRUD.currentOperationURL = CRUD.deleteURL;
break;
default:
CRUD.currentOperationURL = CRUD.serverURL;
break;
}
}
public static void setCurrentTable(int tableIndex){
CRUD.currentTable = tableIndex;
}
public static JsonElement create(Map<String, Object> params) throws IOException {
params.put("table", CRUD.currentTable);
CRUD.setCurrentOperation("create");
return CRUD.send(params);
}
public static JsonElement read(Map<String, Object> params) throws IOException {
params.put("table", CRUD.currentTable);
CRUD.setCurrentOperation("read");
return CRUD.send(params);
}
public static JsonElement update(Map<String, Object> params) throws IOException {
params.put("table", CRUD.currentTable);
CRUD.setCurrentOperation("update");
return CRUD.send(params);
}
public static JsonElement delete(Map<String, Object> params) throws IOException {
params.put("table", CRUD.currentTable);
CRUD.setCurrentOperation("delete");
return CRUD.send(params);
}
private static JsonElement send(Map<String, Object> params) throws IOException {
URL url = new URL(CRUD.currentOperationURL);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8.toString()));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), StandardCharsets.UTF_8.toString()));
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
//Open connection and configure the headers to send to the server...
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
//Send data to server...
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.write(postDataBytes);
//Receive data of the server in UTF-8...
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String charBuild = "";
for(int c = in.read(); c != -1; c = in.read())
charBuild += (char) c;
System.out.println(charBuild);
conn.disconnect();
return new JSON(charBuild).getJsonElement();
}
}
It is worth mentioning that to make things a little easier I am using the GSON
.
On the backend side, the most relevant thing to really mention is that I have these headers defined:
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');
Since really from the beginning of the code in the variable $_POST
I get the data with wrong encoding as I had shown before.
The database as well as all its tables initially had the utf8_spanish2_ci encoding , which later, to test if the problem was resolved, I changed to utf8_general_ci , just like its tables, but it didn't work either...
About the file that handles the connection is built as follows:
connection.php :
<?php
//Función que conectara a la base de datos que necesitemos.
function conectar($host,$DB,$user,$pass){
try {
$conexion = new PDO("mysql:host=$host;dbname=$DB;charset=utf8",$user,$pass);
return $conexion;
} catch (PDOException $e) {
$error = $e->getMessage();
return false;
}
}
?>
This is what I get in full Java
from the backend, so I know something is wrong and the query fails:
{"status":"failed","msg":"Query failed!","data":{":plan":"Habitaci\u00f3n ejecutiva",":email":"[email protected]"}}
Is there a way to get UTF-8 characters to the backend and not unicode?
Additional notes:
- I am using windows 10
- I am using netbeans
- I use a library called GSON
- I use xampp
The solution was something really simple that I didn't realize... what happens is that one of the problems was that I was using a field with a unique key to which I was trying to update the content of another record that already contained that value , so that's why the query failed.
The solution was to remove that unique key , since thinking about it was not very useful to me, but apparently the record is inserted with the correct encoding, so I can assume that in reality, despite the fact that the resulting string seems to have unicode encoding , in the database is correctly saved as UTF-8 , whether it has accents or not now, it is strange since, as I understand it, PHP receives it as a unicode format and not UTF-8 , it even shows it as unicode when the response reaches the frontend.