美好的一天。刚从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 ??,?? Z {srs ?? K ??? XV ?? 4Z‌ ?????'?? n / ?? ^ ?? 4 ?????? w + ????? e? ?????? [?{/ ??,?? WO ??????????????。?。?x ??????? ^^ rax ??]?xb ?? ‌ &&?? 8; ?????} ??? h ???? H5 ?????? v?e?0 ?????-????? g?vN

最佳答案

这是使用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。

07-26 04:25