简体   繁体   English

将JSON中的特殊字符从android发送到PHP

[英]Send special characters in JSON from android to PHP

I want to send a JSON to a PHP file that I have on my server, it works fine except when some field contains a special characters (accents, ñ, etc.). 我想将JSON发送到服务器上的PHP文件,它工作正常,除非某些字段包含特殊字符(重音符号,ñ等)。

Java file: Java文件:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);

    JSONObject json = new JSONObject();

    try {
        // JSON data:
        json.put("id_u", viaje.getID_U());
        json.put("id_vo", viaje.getID_VO());
        json.put("titulo", viaje.getTitulo());
        [...]

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

PHP file: PHP文件:

$json = $_SERVER['HTTP_JSON'];
$data = json_decode($json);

$id_u = $data->id_u;
$id_vo = $data->id_vo;
$titulo = $data->titulo;
[...]

For example, if titulo = "día", $title is empty, but instead whether titulo = "example" works correctly. 例如,如果titulo =“día”,则$ title为空,但是titulo =“ example”是否正常工作。 I do not know how to convert to utf-8 before sending the items, I tried many things and nothing works for me. 在发送邮件之前,我不知道如何转换为utf-8,我尝试了很多事情,但对我来说却无济于事。 Any idea? 任何想法?


EDIT: 编辑:

I could solve the problem. 我可以解决问题。 It was clear that the problem was the encoding. 显然,问题出在编码。 I solved by adding 2 lines to the code: 我通过在代码中添加2行来解决:

Java file: Java文件:

// Post the data:
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);

PHP file: PHP文件:

$json = $_SERVER['HTTP_JSON'];
$cadena = utf8_encode($json);
$data = json_decode($cadena);

thanks for your help! 谢谢你的帮助! :) :)

Sounds like an encoding issue. 听起来像是编码问题。 Try setting the encoding like this: 尝试像这样设置编码:

HttpPost httppost = new HttpPost(builder.getUrl());
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

You can also force the proper encoding on your content like this. 您还可以像这样对内容强制使用正确的编码。 But that's probably not needed here: 但是这里可能不需要:

// Add your data
httppost.setEntity(new UrlEncodedFormEntity(builder
     .getNameValuePairs(), "UTF-8"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM