我正在嘗試從帶有 jaxb 的鏈接中讀取以下xml 。我不斷收到以下例外。檔案中沒有 hr 標簽。
這是我的代碼:
final JAXBContextjaxbContext=JAXBContext.newInstance(EuropeanParliamentMemberResponse.class);
final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
final JAXBElement<EuropeanParliamentMemberResponse> response = jaxbUnmarshaller.unmarshal(new StreamSource(url), EuropeanParliamentMemberResponse.class);
這是例外:
org.xml.sax.SAXParseException; systemId: http://www.europarl.europa.eu/meps/en/full-list/xml; lineNumber: 6; columnNumber: 3; The element type "hr" must be terminated by the matching end-tag "</hr>".]
我究竟做錯了什么?
uj5u.com熱心網友回復:
您收到該錯誤的原因是您在 URL 中使用了錯誤的協議。使用https
而不是http
.
使用http
時,服務器會生成“301 - 永久移動”回應:
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center>
<h1>301 Moved Permanently</h1>
</center>
<hr>
<center>nginx</center>
</body>
</html>
您可以看到<hr>
導致錯誤的標記(它對 XML 的預期內容型別無效)。
如果您使用http
URL,您的瀏覽器將正確處理此問題 - 但您的 JAXB 解組器不會。
假設您的課程中有所有正確的 JAXB 注釋,您問題中的代碼應該可以使用更新的 URL(它適用于我):
https://www.europarl.europa.eu/meps/en/full-list/xml
解決此類問題的一些建議:
在瀏覽器中轉到主頁:
http://www.europarl.europa.eu
- 您將看到您被重定向到一個https
URL。您可以使用 Java
HttpClient
(從 Java 11 開始提供)提取我上面顯示的重定向回應:
String url = "http://www.europarl.europa.eu/meps/en/full-list/xml";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
這將列印回應正文,您可以在其中看到重定向訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/490158.html