【问题标题】:UTF-8 encoding in Volley RequestsVolley Requests 中的 UTF-8 编码
【发布时间】:2015-03-11 23:57:15
【问题描述】:

在我的 Android 应用程序中,我正在使用 Volley JsonArrayRequest 加载 json 数据。这些数据是我自己创建的,我用 Sublime 和 UTF-8 编码保存了它们。当我得到Response 并填写我的ListView 时,文本显示不正确(变音符号)。这就是我的请求的样子:

JsonArrayRequest request = new JsonArrayRequest(targetUrl,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(final JSONArray response) {
                        try {
                            fillList(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(request);

当我用这种方法加载完全相同的数据时,所有文本都正确显示:

final StringBuilder builder = new StringBuilder();
        final HttpClient client = new DefaultHttpClient();
        final HttpGet httpGet = new HttpGet(request);
        try {
            final HttpResponse response = client.execute(httpGet);
            final StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                final HttpEntity entity = response.getEntity();
                final InputStream content = entity.getContent();
                final BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {

            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

所以对我来说,我的 json 文件的编码似乎没有问题。如何解决 Volley 中的编码问题?

【问题讨论】:

  • 对于它的价值,我使用了 UTF-8 编码的 JSON 文件并且它工作正常。您在提供文件时是否设置了“Content-Type”标头? Volley 应该阅读并适当地构建它的响应。
  • 不,我没有设置这个标题。我不知道我必须这样做。 DoO 你有我的例子吗?
  • 您是否在服务器上提供 JSON 文件?无论您在何处处理对这些文件的请求,您都希望使用类似“Content-Type text/json charset=utf-8”之类的内容指定返回标头。
  • 我刚刚通过 FTP 将 JSON 文件上传到我的私人网络空间。

标签: android encoding utf-8 android-volley


【解决方案1】:

如果您知道您请求的所有文件绝对都是 UTF-8 格式,听起来就像您所做的那样,那么您可能会考虑强制您的 Volley 请求返回 UTF-8 格式的字符串。您可以通过继承标准 JSON 请求来完成此操作。像这样的:

public class Utf8JsonRequest extends JsonRequest<JSONObject> {
    ...
    @Override
    protected Response<JSONObject> parseNetworkResponse (NetworkResponse response) {
        try {
            String utf8String = new String(response.data, "UTF-8");
            return Response.success(new JSONObject(utf8String), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            // log error
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            // log error
            return Response.error(new ParseError(e));
        }
    }
}

【讨论】:

  • 我现在看到您使用的是JsonArrayRequest。您可以改为将其子类化。我没有方便的语法,但它会非常相似。
  • 谢谢,我试试看!
  • 它有效。在我的 StringRequest 中覆盖 parseNetworkResponse 也解决了我在加载一些 XML 提要时遇到的问题。谢谢@xaevinx
  • 嘿@JensJensen,这如何解决您的问题?我尝试扩展 JsonArrayRequestJsonRequest&lt;JSONArray&gt; 都没有工作。我仍然得到“??????”作为回应。当我转到 Chrome 中的php 服务时,json 显示正确,但是在调试时,读取接收到的 json 时它似乎是????所以应该又是Volley的错了。奇怪的是,我们必须像在 JsonRequest 类中那样覆盖 Volley 的编码,它使用的是 UTF8 - protected static final String PROTOCOL_CHARSET = "utf-8";
  • 为什么HttpHeaderParser.parseCharset(response.headers) 不能正常工作?
【解决方案2】:

我有同样的问题,我使用 UTF-8 字符集解决它。

String str = "";
try {
     str = new String(strFromService.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {

 e.printStackTrace();
}

String decodedStr = Html.fromHtml(str).toString();

我希望这对你有用

【讨论】:

    【解决方案3】:

    不要在 onResponse 块中使用 try{} catch,这会给我的代码带来一些问题,而不是你可以这样实现。

    @Override 
    onResponse(String s) {
    
    s= fixEncoding(s);
    Toast.makeToast(this,s,Toast.LENGTH_LONG).show();
    
    }
    

    我认为你会得到所需的结果

     public static String fixEncoding(String response) {
                try {
                    byte[] u = response.toString().getBytes(
                            "ISO-8859-1");
                    response = new String(u, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return null;
                }
                return response;
            }
    

    【讨论】:

      【解决方案4】:

      这对我来说是一种魅力,我刚刚根据@Muhammad Naeem 的回答创建了一个静态方法,谢谢 Muhammed..

      public static String fixEncodingUnicode(String response) {
          String str = "";
          try {
              str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
          } catch (UnsupportedEncodingException e) {
      
              e.printStackTrace();
          }
      
          String decodedStr = Html.fromHtml(str).toString();
          return  decodedStr;
      }
      

      【讨论】:

        【解决方案5】:

        在服务器部分中指定内容类型为“text/html;charset=utf-8”的utf-8

        【讨论】:

          【解决方案6】:

          另一种方法:您可以通过这行代码对整个响应进行编码。

          newStr = URLDecoder.decode(URLEncoder.encode(oldStr, "iso8859-1"),"UTF-8");
          

          我已将整个响应字符串编码为 UTF-8,因为我知道 volley 默认编码方法是 iso8859-1

          【讨论】:

            【解决方案7】:

            两天前我遇到了同样的问题,我已经尝试了我朋友刚刚说的每件事,这是同样的问题,我尝试了很多卑鄙的事情.. 我的文件是用 php 编写的,并使用 volley 以 json 格式获取数据,我按照这些步骤解决了问题..

            1. 在你的数据库中执行查询之前写下这个查询

              mysqli_query($this->connection,"set_NAMES_utf8");

            2. 如果是 php,请在文件中使用此标头

              header('Content-Type: application/json ; charset=utf-8 ');

            3. 当您根据 php 回显 json 时,可以解决此问题 在json_encode($json,JSON_UNESCAPED_UNICODE)中使用这个特殊字符

              希望对你有帮助

            【讨论】:

              【解决方案8】:

              在 volley 的响应中添加这行代码:

               public void onResponse(String response) 
                  {
              
                   if (response != null) 
                    {
                      response=new String(response.getBytes("ISO-8859-1"), "UTF-8");
                    }
                 }
              

              【讨论】:

                【解决方案9】:

                我只是在我的 public void onResponse(){} 方法中使用了这行代码,它工作得很好。

                          if (response != null){
                                try {
                                    response=new String(response.getBytes("ISO-8859-1"), "UTF-8");
                
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                

                【讨论】:

                  【解决方案10】:
                  StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
                          @Override
                          public void onResponse(String response) {
                              if (response != null){
                                  dialog.dismiss();
                                  try {
                                      response=new String(response.getBytes("ISO-8859-1"), "UTF-8");
                                      JSONArray jsonArray = new JSONArray(response);
                                      parseArray(jsonArray);
                  
                                  } catch (JSONException | UnsupportedEncodingException e) {
                                      e.printStackTrace();
                                  }
                              }
                  
                          }
                      }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2016-02-01
                    • 2011-10-30
                    • 2012-11-07
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多