【问题标题】:Android PHP POST accents paramters failedAndroid PHP POST 重音参数失败
【发布时间】:2014-05-04 15:02:51
【问题描述】:

我在一个项目中工作,我们在客户端有一个 android 应用程序,而服务器端是用 PHP 管理的。客户端应该向服务器发送信息,它应该回复一个包含结果的 json。在我们使用一些特殊字符之前,一切都找到了,我不知道如何解决这个问题。

我已经验证了 Apache 和 PHP 设置,并且两者都使用 UTF-8 作为默认字符集。

我面临的问题是:

  1. 当 $_POST 中的值包含特殊字符时,我的 PHP 代码无法自行管理它们。在我使用它之前,我应该在 PHP 中使用 urldecode() 对其进行解码吗?这些值通过 URLEncoder.econde(myvalue,"UTF-8") 发送到服务器。请参阅下面的代码。
  2. 我的 php 代码返回一个 json 对象。如果对象中没有特殊字符,一切正常,但如果它包含一些重音或类似字符,则无法管理该对象。

这是我的代码

安卓端

public class HelperClassJSONDownload {
public HelperClassJSONDownload(){

}

// Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    public JSONObject downloadJSON (String myurl,List<NameValuePair> params) {
        InputStream inputStream = null;
        JSONObject jsonObject = null;
        String json = "";

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);//We need it to set parameters
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("charset", "utf-8");



            //Writer w=new OutputStreamWriter(
            //      conn.getOutputStream(), "UTF-8");
            //w.write(getQuery(params).toString());
            //w.flush();
            //w.close();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();
            //END SETTING PARAMETERS REQUEST



            // Starts the query 
            conn.connect();
            int response = conn.getResponseCode();

            switch (response){
                case 200:
                case 201:
                     inputStream = conn.getInputStream();
                     BufferedReader reader = new BufferedReader
                             (new InputStreamReader(inputStream,  "UTF-8"), 8);
                     StringBuilder sb = new StringBuilder();
                     String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                            sb.append(line + "\n");
                        }
                        json = sb.toString();
                        jsonObject = new JSONObject(json);
                        return jsonObject;


                default:
                    return null;
                }


        } catch(IOException e){
            return null;
        } catch(JSONException e1){
            return null;
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e2) {
                    // TODO: handle exception
                }

            } 
        }
    }


    /**
     * This method create the String we will pass with the parameters
     * @param params
     * @return the string used for  for the parameters
     * @throws UnsupportedEncodingException
     */
    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }

     }

这是PHP代码,函数generalCheckUserData()检查一些值并比较客户端提供的信息。如果客户端提交一些特殊字符是无法管理的。即如果我们需要比较提交的 á 和 a´ 这个函数不起作用 if($_POST['values'] == á) 此外,如果返回的 json 包含一些特殊字符,它也不起作用。

我希望这些信息足够了

 public function __construct() {

    $this->response = array("tag" => $this->tag, "success" => 0, "error" => 0);

    if ($this->generalCheckUserData() && (isset($_POST['tag']) && $_POST['tag'] == 'register')){
        $this->registerNewUser($_POST['user_email'], $_POST['user_password_new'], $_POST['user_password_repeat'],
                $_POST['user_first_name'], $_POST['user_last_name_1'], $_POST['user_last_name_2'], $_POST['user_telephone']
                ,$_POST['user_city'], $_POST['user_province'], $_POST['user_postal_code'], $_POST['user_country']);
    } else  {
        //we create an array where to storage the information returned to the client
        $this->response['error'] = 1;
        $this->response['error_type'] = 1;
        $this->response["error_msg"] = $this->mes;
        echo json_encode($this->response);
    }
}

【问题讨论】:

    标签: php android json utf-8 diacritics


    【解决方案1】:

    最后我发现问题出在 Zend Studio 设置中。请查看此Encoding in Eclipse 表单以获取更多详细信息。

    【讨论】:

      【解决方案2】:

      我不确定这会在哪里有所帮助,但根据我的一般知识如何添加此连接属性 Accept-Encoding 并将其设置为 utf8 并在连接区域的 PHP 代码中将排序规则设置为 UTF8

      【讨论】:

      • 嗨,Gamal,我想试试你的,但请你澄清一下“连接区域中的 PHP 代码,将排序规则设置为 UTF8”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 2023-03-07
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      相关资源
      最近更新 更多