我正在尝试在JAVA中以给定的纬度和经度提取酒店名称的数据。我收到以下错误:[致命错误]:1:1:prolog中不允许内容。 这是我尝试提取信息的代码和URL。有关这个问题的任何建议吗?
URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US¤cyCode=USD&latitude=51.514&longitude=-0.269"");
InputStream is = url.openStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
NodeList itemList =
doc.getElementsByTagName("HotelSummary");
Node itemNode;
Element itemElt;
for(int k=0; k < itemList.getLength(); k++)
{
itemNode = itemList.item(k);
if(itemNode.getNodeType() == Node.ELEMENT_NODE) {
itemElt = (Element) itemNode;
System.out.println("Hotel name: "+itemElt.getElementsByTagName("name").item(0).getTextContent());
答案 0 :(得分:1)
如果您运行以下代码,您将看到您获取的数据不是XML,而是JSON。
import java.net.URL;
import java.io.InputStream;
public class Demo {
public static void main(String[] args) throws Exception {
URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US¤cyCode=USD&latitude=51.514&longitude=-0.269");
InputStream is = url.openStream();
int next = is.read();
while(next != -1) {
System.out.print((char) next);
next = is.read();
}
}
}
您可以使用HttpURLConnection
以XML格式请求数据:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStream;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
public class Demo {
public static void main(String[] args) throws Exception {
URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US¤cyCode=USD&latitude=51.514&longitude=-0.269");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream is = connection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
}
}