String Encoding problem in Webview

2019-02-02 15:26发布

I am getting the response from web service shown below

<html><head>
<style type="text/css">
    body{
         color: #FFFFFF; 
         background-color: #000000;
    }
 </style>
</head>
<body><center><div>
Ricardo Viana Vargas  
09-14 Ricardo Viana Vargas é especialista em  gerenciamento de projetos, portfólio e riscos. Foi, nos últimos 15 anos, responsável por mais de 80 projetos de grande porte em diversos países, nas áreas de petróleo, energia, infraestrutura, telecomunicações, informática e finanças, com um portfólio de investimentos gerenciado superior a 18 bilhões de dólares. Foi o primeiro voluntário latino-americano a ser eleito para exercer a função de presidente do conselho diretor (Chairman) do Project Management Institute (PMI), maior organização do mundo voltada para a administração de projetos, com cerca de 500 mil membros e profissionais certificados em 175 países.  Ricardo Vargas escreveu dez livros sobre gerenciamento de projetos, publicados em português e inglês, com mais de 240 mil exemplares vendidos mundialmente. Recebeu em 2005 o prêmio PMI Distinguished Award pela sua contribuição para o desenvolvimento do gerenciamento de projetos e o PMI Professional Development Product of the Year pelo workshop PMDome®, considerado a melhor solução do mundo para o ensino do gerenciamento de projetos. É professor de gerenciamento de projetos em diversos cursos de MBA, participando do conselho editorial de revistas especializadas no Brasil e nos Estados Unidos. Vargas é revisor reconhecido da mais importante referência no mundo sobre gerenciamento de projetos, o PMBOK Guide. Foi também chair da tradução oficial do PMBOK para o português. Engenheiro químico e mestre em Engenharia de Produção pela UFMG, Ricardo Vargas tem também o Master Certificate in Project Management pela George Washington University, além de ser certificado pelo PMI como Project Management Professional (PMP) e pela Scrum Alliance como Certified Scrum Master (CSM). Participou do programa de negociações para executivos da Harvard Law School e tem formação executiva de estratégia e inovação pelo Massachusetts Institute of technology (MIT).Durante onze anos, a partir de 1995, desenvolveu em conjunto com dois sócios um dos mais sólidos negócios de tecnologia, gerenciamento de projetos e terceirização do mercado brasileiro, que contava com 4,000 colaboradores e gerava uma receita anual de 50 milhões de dólares em 2006, quando Ricardo Vargas vendeu sua participação para se dedicar integralmente à internacionalização de seus trabalhos em gerenciamento de projetos. É membro da Association for Advancement of Cost Engineering (AACE), da American Management Association (AMA), da International Project Management Association (IPMA), do Institute for Global Ethics e da Professional Risk Management International Association (PRMIA).
</div> </center>
</body>
</html>

The Output of webview is shown below

enter image description here

How can i show exact character in webview ?

the code i used for web view shown below

System.out.println("strContent is :: " + strContent);
                    WebView wv = (WebView) findViewById(R.id.webview_portugage);
                    wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
                    wv.loadData(strContent, "text/html", "UTF-8");

6条回答
乱世女痞
2楼-- · 2019-02-02 15:54

Based in your original code, you can use two options:

Using loadDataWithBaseURL() :

wv.loadDataWithBaseURL(null, strContent, "text/html", "UTF-8", null);

or using loadData() :

wv.loadData(strContent, "text/html; charset=utf-8", "UTF-8");
查看更多
时光不老,我们不散
3楼-- · 2019-02-02 16:04

1) Use WebView.loadDataWithBaseURL, it behaves different (better) than WebView.loadData

2) Try to replace "UTF-8" encoding by some other, e.g. US-ASCII. Best is to determine what encoding is really used in text that you try to display.

查看更多
家丑人穷心不美
4楼-- · 2019-02-02 16:09

I fixed my problems with using "text/html; charset=utf-8" as MIME-type at WebView.loadData

EDIT: Thanks to AndyD for his comment. Unfortunately this tip does not work on every device (I think it depends on the used webkit version). Using WebView.html#loadDataWithBaseURL works on every (tested) device.

查看更多
聊天终结者
5楼-- · 2019-02-02 16:10

I had the same issue in past, the WebView.loadData() with MIME type "text/html; charset=utf-8" didn't work for me. But the only problem was that I hadn't set the "meta http-equiv="Content-Type" content="text/html; charset=utf-8" in my test HTML.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-02-02 16:15

This code worked for me.

String base64EncodedString = null;
                        try {
                            base64EncodedString = android.util.Base64.encodeToString((preString+mailContent.getBody()+postString).getBytes("UTF-8"), android.util.Base64.DEFAULT);
                        } catch (UnsupportedEncodingException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        if(base64EncodedString != null)
                        {
                            wvMailContent.loadData(base64EncodedString, "text/html; charset=utf-8", "base64");  
                        }
                        else
                        {
                            wvMailContent.loadData(preString+mailContent.getBody()+postString, "text/html; charset=utf-8", "utf-8");
                        }
查看更多
Fickle 薄情
7楼-- · 2019-02-02 16:19
content.loadData(htmlsource, "text/html; charset=utf-8", null);

It worked for me :)

查看更多
登录 后发表回答