Search code examples
javaphpandroidposthttp-accept-language

What is wrong when i try to post String with scandinavian characters from Android to Php, like ÅÄÖ


I can't find any reason why my scandinavian characters passed to php isn't shown and stored correctly.

When I use my web application, scandinavian characters works correctly with php and database.

If i write message to database from webapp and load it to android app, characters comes correctly.

In android

String message = "Tässä"

try {

    // open a connection to the site
    URL url = new URL("own_url");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();


    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "");
    con.setRequestProperty("Accept-Language", "fi, en-US,fi;q=0.6, en;q=0.5");
    con.setRequestProperty("Accept-Charset", "UTF-8");

    // Send post request
    con.setDoOutput(true);

    String urlParameters = "message=" + message;

In PHP

$message = $_POST['message'];
error_log($message);

error_log shows it like T\xe4ss\xe4

mysqli_set_charset($con, 'utf8');
date_default_timezone_set('UTC');

$sql = "INSERT INTO messages SET message='$message'";
mysqli_query($con, $sql);

In database it is T?ss

EDIT

Changed query generation to prevent SQL-injection, thanks to user2864740 suggestion.

$stmt = $con->prepare("INSERT INTO messages (message) VALUES (?)");
$stmt->bind_param("s", $message);
$stmt->execute();

Solution

  • I found solution for my problem, I needed to have urlParameters to be byte[] like this.

    String urlParameters = "message=" + message;
    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
    
    DataOutputStream wr = new DataOutputStream( con.getOutputStream()){};
    wr.write( postData );
    

    But there is problem with API lower than 19, with this:

    StandardCharsets.UTF_8
    

    Field requires API level 19 (Current min is 14): java.nio.charset.StandardCharsets#UTF_8