0

我编写此代码是为了从站点获取 html 源代码。

        HttpURLConnection connection;
        OutputStreamWriter request = null;

        URL url = null;
        String response = null;
        String parameters = "aranan="+et.getText();

        try
        {
            url = new URL("http://www.fragmanfan.com/arama.asp");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            // Response from server after login process will be stored in response variable.
            response = sb.toString();
            // You can perform UI operations here
            browser.loadDataWithBaseURL(null, response,"text/html", "UTF-8", null);

            isr.close();
            reader.close();
        }
        catch(IOException e)
        {
            // Error
        }
    }
});

但是有一个问题。它是:响应(具有html源的变量)不是utf-8格式。我该如何解决这个问题?谢谢。

4

2 回答 2

0

. . .

 InputStreamReader isr = new InputStreamReader(connection.getInputStream(),"ISO-8859-9"); 

. . .

于 2012-04-11T11:30:54.917 回答
-1

由于您的响应似乎是单个字符串中的 HTML 网页,因此您应该确保页面的 head 标签包含定义编码的标签。如果不是,您可以自己将其附加到您的 StringBuilder。您可以这样做:

final StringBuilder sb = 
new StringBuilder("<html><head>"+ "<meta http-equiv=\"content-type\"content=\"text/html;charset=utf-8\" />"+ "</head><body>");
while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
response = sb.toString();
sb.append(response);
sb.append("</body></html>");

然后您可以正确地将您的 HTML 加载到您的 webview / 浏览器。(这对我有用,所以我确定它确实有效=])

pd 确保接受正确回答您问题的答案,以便人们继续回答您未来的问题。 https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work

于 2012-04-11T00:22:25.203 回答