【问题标题】:Android HTTP Request EncodingAndroid HTTP 请求编码
【发布时间】:2013-08-07 17:07:10
【问题描述】:

我想在我的 Android 应用程序中执行 HTTPRequest,使用以下代码:

BufferedReader in = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI("http://www.example.de/example.php"));
        HttpResponse response = client.execute(request);
        in = new BufferedReader
        (new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String page = sb.toString();

        System.out.println(page);
        return page;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                    e.printStackTrace();
            }
        }
   }

我调用的网页是一个返回字符串的 php 脚本。我的问题是特殊字符(ä、ü、ö、€ 等)显示为带框的问号。我怎样才能得到这些字符?

我认为这是编码的问题(德国应用程序 -> UTF-8?)。

【问题讨论】:

  • 如果返回正确的字符编码,您能否验证浏览器中的内容。
  • 我的浏览器显示内容正确。
  • 请通过设置检查,request.setHeader("Content-type", "text/html; charset=utf-8");.
  • 做到了,但不起作用...我的浏览器说页面编码为 Cp1252 (Windows-1252)。

标签: java android encoding utf-8 httprequest


【解决方案1】:

我玩过你的代码,对抗http://www.google.de。

我能够“破解”某些东西,但不确定它是否是最优雅的解决方案。

行后:

HttpResponse response = client.execute(request);

...我添加了:

HttpEntity e = response.getEntity();
Header ct = e.getContentType();
HeaderElement[] he = ct.getElements();
if (
    he.length > 0 
        && he[0].getParameters().length > 0
        && he[0].getParameter(0) != null 
        && he[0].getParameter(0).getName().equals("charset")
    ) {
    String charset = he[0].getParameter(0).getValue();
    // with google.de, will print ISO latin ("ISO-8859-1")
    Log.d("com.example.test", charset);
}

...然后您可以添加字符集表示,或其Java等效项作为InputStreamReader构造函数调用的第二个参数:

in = new BufferedReader(
    new InputStreamReader(
        response.getEntity().getContent(), 
        charset != null ? charset : "UTF-8"
);

让我知道这是否适合您。

还要注意,为了检查 Java 字符集等价性,您可以使用 Charset.forName(String charsetName) 并捕获相关的 Exceptions(然后恢复为 Charset.defaultCharset() 或 UTF-8 等。在您的catch 声明中)。

【讨论】:

  • @user2174738 我编辑了答案以检查he[0] 返回的NameValuePair 数组,这可能会导致您的ArrayIndexOutOfBoundsException。但是,您的情况意味着您的响应实体中可能没有标题元素。在这种情况下,我想可能很难检测到响应的编码。您必须确定它是哪种编码,并像以前一样将其添加为 InputStreamReader 初始化的参数。
  • @user2174738 ...既然你在问题中说你的网页用ANSI编码,那么在你的InputStreamReader参数列表中使用它作为字符集编码。
【解决方案2】:

也许你可以在显示到控制台时尝试设置编码。某些字符从服务器正确返回,但无法在控制台中显示。

String page = sb.toString();
PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(page);

【讨论】:

  • 不,这不起作用:(我也在控制台中得到问号。
  • 确保您的服务器返回“UTF-8”字符集
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2013-06-13
相关资源
最近更新 更多