繁体   English   中英

齐射请求中带有奇怪字符的json请求数据

[英]Data of json request with strange characters in volley request

我正在发出一个 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);
}

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

请尝试使用此代码以 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();
}

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

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

我也使用 Volley,这种方式对我有用。

问候。

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

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));
        }
    }

}

暂无
暂无

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

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