-1

我从 android 中的 Json 获取数据,日期获取并保存在 String 变量中。但是当使用 DecodeUrl 时,它的错误:

错误:java.lang.IllegalArgumentException:40 处的无效 % 序列:

我的代码:

@SuppressLint("NewApi")
    public String JsonReguest(String url) {
        String json = "";
        String result = "";
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object

        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept", "application/json");
        httpget.setHeader("Content-Type", "application/json");


        HttpResponse response;
        try {


            response = httpclient.execute(httpget);
            response.setHeader("Content-Type","UTF-8");
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();

                result = convertStreamToString(instream);
                InputStream stream = new ByteArrayInputStream(result.getBytes("UTF-8"));
                result = convertStreamToString(stream);

                // String encode_url=URLEncoder.encode(result,"UTF-8");
                // String decode_url=URLDecoder.decode(encode_url,"UTF-8");

                //result=decode_url;
                //String decodedUrl = URLDecoder.decode(result, "UTF-8");
                result=URLDecoder.decode(result);

            }
        } catch (Exception e) {
            Log.e("Error", e.toString()); 
        }
        return result;
    }

    public static String convertStreamToString(InputStream is) {


        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

json 的简单文本:

{"CategoryID":11,"ParentID":0,"Title":"%u062E%u0648%u062F%u0631%u0648","PicAddress":""},{"CategoryID":16,"ParentID":0,"Title":"%u0627%u0645%u0644%u0627%u0643%20","PicAddress":""}

这一行崩溃了:result=URLDecoder.decode(result);

如何解决问题。

4

2 回答 2

2

首先解码指定您的编码

String result = URLDecoder.decode(url, "UTF-8");

然后转到http://json.org/,向下滚动并选择支持的 json 解析 Java 库之一

于 2013-09-20T14:47:01.570 回答
2

正如 Selvin 所评论%uxxxx的,它不是标准的 Url 编码字符串,因此很明显会出现错误

你有两个选择:

  1. 联系服务提供商以修复她的 url 编码字符串并URLDecoder.decode在您的代码中使用
  2. 为此类字符串编写自定义解码器

PS 把你的问题问得更清楚,以免得到负分

于 2013-09-20T17:38:06.027 回答