过去,类似下面的代码可以很好地从银行的 XML 数据中获取一两个汇率 - 无需应用 XML 解析器的开销。
但是现在读取的字符似乎与该 URL 无关,尽管在我的浏览器中输入网址时,页面看起来仍然正常。
String adr = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
try {
URL url = new URL(adr);
InputStream in = url.openStream();
byte[] b = new byte[1024];
int l = 0;
while ((l = in.read(b)) != -1) {
String s = new String(b, 0, l);
System.out.println(l);
System.out.println(s);
}
in.close();
} catch (MalformedURLException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
发生了什么以及我必须做什么才能获取 xml 数据?
最佳答案
页面已移动 - 使用 https url ("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml ")
顺便说一句,为什么你要以如此复杂的方式从 URL 读取?使用 RestTemplate:
RestTemplate restTemplate = new RestTemplate();
String url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
System.out.println(response.getBody());
关于java - 如何从网上读取欧洲央行货币汇率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498216/