如何解码android中的特殊字符?

时间:2013-10-01 10:42:00

标签: android encoding utf-8 character-encoding xml-parsing

在我的Android应用程序中,我正在使用套接字并获取XML作为响应。我得到的XML如下:

 <response>
     <result>
        <id>90</id>
        <name>J�nna</name>
     </result>
 </response>��

以下是获取回复的代码:

 PrintWriter  writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()) )  ;
 BufferedReader reader = new BufferedReader( new InputStreamReader( socket.getInputStream(), "UTF-8") );

 writer.write(sMessage);
 writer.flush();

 StringBuilder sb = new StringBuilder();
 boolean dataStreamStarted = false;
 int sleepCounter = 0;
 int sleepMaxCounter = 50;
 int sleepMaxDataCounter = 3;
 int sleepTime = 50;
 long startTime = System.currentTimeMillis();
 while( true )
 {
     if ( reader.ready() )
     {
         sb.append( (char) reader.read() );
         dataStreamStarted = true;
     }
     else
     {
         Thread.sleep( sleepTime );
         if ( dataStreamStarted && (sleepCounter >= sleepMaxDataCounter) )
         {
             break;
         }
         else
         {
             if (sleepCounter >= sleepMaxCounter)
             {
                 break;
             }
         }
         sleepCounter++;
     }
 }
 long endTime = System.currentTimeMillis();

 writer.close();
 reader.close();
 socket.close();

 response = sb.toString();

我尝试使用以下代码解码此字符串:

 String str = URLDecoder.decode(response, "UTF-8");

但它没有任何区别。字符串看起来仍然相同由于这些字符,我不能解析这个字符串。知道我怎么解决它?我搜索了很多,我找到的任何解决方案都没有用。提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试此方法以支持UTF-8作为响应

public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {

        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }

        InputStream instream = entity.getContent();

        if (instream == null) {
            return "";
        }

        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(

            "HTTP entity too large to be buffered in memory");
        }

        StringBuilder buffer = new StringBuilder();

        BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

        } finally {
            instream.close();
            reader.close();
        }
        return buffer.toString();

    }