1

再会。刚刚从objective-c切换到java并尝试将url内容正常读取为字符串。阅读大量帖子,但仍然会产生垃圾。

public class TableMain {

    /**
     * @param args
     */
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws Exception {
        URL url = null;
        URLConnection urlConn = null;

        try {
            url = new URL("http://svo.aero/timetable/today/");
        } catch (MalformedURLException err) {
            err.printStackTrace();
        }
        try {
            urlConn = url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream(), "UTF-8"));
            StringBuilder strB = new StringBuilder();
            String str;
            while (null != (str = input.readLine())) {
                strB.append(str).append("\r\n");
                System.out.println(str);
            }
            input.close();
        } catch (IOException err) {
            err.printStackTrace();
        }
    }
}

怎么了?我得到这样的东西

??y??'??)j1???-?q?E?|V??,??< 9??d?Bw(?э?n?v?)i?x????? Z????q?MM3~??????G??љ??l?U3"Y?]???? zxxDx????t^???5???j? ?k??u?q?j6?^t???????W??????????~?????????o6/ ?|?8??{? ??O????0?M>Z{srs??K???XV??4Z‌​??'??n/??^??4????w+?????e? ??????[?{/??,??WO???????????.?.?x???????^?rax??]?xb??‌ ​& ??8;?????}???h????H5????v?e?0?????-?????g?vN

4

2 回答 2

-1

下面是一个使用 HttpClient 的方法:

 public HttpResponse getResponse(String url) throws IOException {
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    return httpClient.execute(new HttpGet(url));
}


public String getSource(String url) throws IOException {
            StringBuilder sb = new StringBuilder();
            HttpResponse response = getResponse(url);
            if (response.getEntity() == null) {
                throw new IOException("Response entity not set");
            }
            BufferedReader contentReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = contentReader.readLine();

            while ( line != null ){
                sb.append(line)
                  .append(NEW_LINE);
                line = contentReader.readLine();
            }
            return sb.toString();
    }

编辑:我编辑了响应以确保它使用 utf-8。

于 2012-09-25T21:52:04.690 回答
-1

这是以下原因的结果:

  1. 您正在获取 UTF-8 编码的数据
  2. 您没有指定,但我猜您正在将其打印到 Windows 系统上的控制台

数据被正确接收和存储,但是当您打印它时,目的地无法呈现俄语文本。除非最终的显示处理程序能够呈现所涉及的字符,否则您将无法仅将文本“打印”到标准输出。

于 2012-09-25T22:13:17.170 回答