Unable to extract xml data from website using JAVA

前端 未结 1 549
长情又很酷
长情又很酷 2020-12-12 04:49

I\'m trying to extract data for the hotel names at the given latitude and longitude in JAVA. I\'m getting the following error: [Fatal Error] :1:1: Content is not allowed in

相关标签:
1条回答
  • 2020-12-12 05:03

    What's Going Wrong

    If you run the following code, you will see the data you are getting back is not XML, but 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&currencyCode=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();
            }
        }
    
    }
    

    Getting the Data as XML

    You can use an HttpURLConnection to request the data as 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&currencyCode=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);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题