【问题标题】:Data of json request with strange characters in volley request凌空请求中带有奇怪字符的json请求数据
【发布时间】:2015-07-02 00:26:58
【问题描述】:

我正在发出 Json 请求,我获取数据并将其放置在列表视图中,但我得到的一些字符串带有重音符号或“ç”,并且显示不正确。 例如,字符串是“Bragança”,我收到“Bragança”或“à”并得到“Ô。如果我在浏览器中发出请求,一切正常。 我的请求。

public void makeJsonArrayRequest() {

    RequestQueue queue = AppController.getInstance().getRequestQueue();
    queue.start();
    JsonArrayRequest Req = new JsonArrayRequest(urlJsonObjUtilizadas,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    // Parsing json

                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject ementaObj = response.getJSONObject(i);
                            Ementa ementa = new Ementa();


                            ementa.setCantina(ementaObj.getString("cantina"));
                            ementa.setDescricao(ementaObj.getString("descricao"));
                            ementa.setEmenta(ementaObj.getString("ementa"));
                            ementa.setPreco(ementaObj.getInt("preco"));

                            ementaItems.add(ementa);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // notifying list adapter about data changes
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());

        }
    }) {
        //**
        // Passing some request headers
        //*
        @Override
        public Map<String, String> getHeaders()  {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=UTF-8");
            return headers;
        }
    };
    // Add the request to the RequestQueue.
    AppController.getInstance().addToRequestQueue(Req);
}

【问题讨论】:

  • 这是错字吗? ementa.setPreco(ementaObj.getInt("preco"));其他项目是字符串。
  • 是的。 preco 是一个整数

标签: java android json android-studio android-volley


【解决方案1】:

我认为这是因为错误的内容类型编码标头。您应该使用 UTF-8 作为编码。也许这在浏览器中有效,因为标头不区分大小写(与 Android 不同)。 查看here 以获取解决方案。本质上,它们是手动覆盖字符集。

【讨论】:

    【解决方案2】:

    请尝试使用此代码发送和接收带有 utf-8 编码的 JSON:

    try {
        URL url = new URL("your url");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
        conn.setDoOutput(true);
    
        OutputStreamWriter writer = new OutputStreamWriter(
                conn.getOutputStream(), "UTF-8");
        String request = "your json";
        writer.write(request);
        writer.flush();
        System.out.println("Code:" + conn.getResponseCode());
        System.out.println("mess:" + conn.getResponseMessage());
    
        String response = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            response += line;
        }
    
        System.out.println(new String(response.getBytes(), "UTF8"));
        writer.close();
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    【讨论】:

    • 你能告诉我如何把它放在我的代码中吗?谢谢。
    【解决方案3】:

    您应该将请求标头字符集添加到 UTF-8。例如,如果您的请求将是 json,则应将此标头添加到请求中:

    “内容类型”:“应用程序/json;utf-8”

    我也使用 Volley,这种方式适合我。

    问候。

    【讨论】:

    • 对不起,我是 android 新手,如何在我的代码中添加请求标头?谢谢。
    • 舒尔,我会给你一个真实的例子,检查另一个答案。
    • 我已经将标头放入请求中,但结果是一样的。我用新代码更新了我的问题。
    • 更改这一行:headers.put("Content-Type", "application/json; charset=utf-8"); To: headers.put("Content-Type", "application/json; charset=iso-8859-1");问题可能是字符集,告诉我它是否有效。问候
    【解决方案4】:

    检查这个示例,我正在使用这种方式,查看标题部分

    public class Estratek_JSONString extends JsonRequest<String>{
    Activity Act;
    Priority priority;
    
    public Estratek_JSONString(int m, String url, JSONObject params,
            Listener<String> listener, ErrorListener errorListener,Activity act, Priority p)  {
        super(m,url,params.toString(),listener,errorListener); 
    
        this.Act=act;
        this.priority=p;    
    } 
    public Estratek_JSONString(int m, String url,
            Listener<String> listener, ErrorListener errorListener,Activity act, Priority p)  {
        // super constructor
    
        //super(m,url,params.toString(),listener,errorListener);
        super(m,url,null,listener,errorListener);
    
        this.Act=act;
        this.priority=p;    
    } 
    
    @Override
    public Map<String, String> getHeaders()  {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("Authorization", "Bearer "+Tools.Get_string(Act.getApplicationContext(),Global_vars.Access_token));
            return headers;
        }
    
    //it make posible send parameters into the body.
      @Override
      public Priority getPriority(){
        return priority;
     }
    
      @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                return Response.success(new String(jsonString),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) { 
                return Response.error(new ParseError(e));
            }
        }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多