繁体   English   中英

如何在Java或android中解码字符串?

[英]How to Decode String in Java or android?

我从android中的Json获取数据,获取并保存在String Variable.date中,但是使用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);

如何解决问题。

首先解码指定您的编码

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

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

正如Selvin所说, %uxxxx不是标准的Url编码的字符串,因此很容易出错。

您有2个选择:

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

PS可以更清楚地问您的问题,以避免产生负面影响

暂无
暂无

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

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