1

我想将 JSON 发送到我服务器上的 PHP 文件,它工作正常,除非某些字段包含特殊字符(重音符号、ñ 等)。

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 文件:

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

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

例如,如果titulo = "día",则$title 为空,而是titulo = "example" 是否正常工作。在发送项目之前我不知道如何转换为 utf-8,我尝试了很多东西,但对我没有任何作用。任何想法?


编辑:

我可以解决问题。很明显,问题出在编码上。我通过在代码中添加 2 行来解决:

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 文件:

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

感谢您的帮助!:)

4

1 回答 1

2

听起来像是编码问题。尝试像这样设置编码:

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

您还可以像这样强制对您的内容进行正确的编码。但这可能在这里不需要:

// Add your data
httppost.setEntity(new UrlEncodedFormEntity(builder
     .getNameValuePairs(), "UTF-8"));
于 2013-08-13T13:14:36.767 回答