Problem fetching XML file in Java

前端 未结 4 1133
感情败类
感情败类 2021-01-07 13:29

I am trying to use Google\'s unofficial weather API in an Android Application.

I use this code:

//get the text from the edit text
    userZip = zipCo         


        
4条回答
  •  时光取名叫无心
    2021-01-07 14:30

    I think you need to open the connection with the url and get the inputstream for this to work. I would try this:

     URL googleWeatherService = null;
     URLConnection conn = null;
    try {
        googleWeatherService = new URL(link);
        conn = googleWeatherService.openConnection();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 
    SAXBuilder parser = new SAXBuilder();
    try {
        doc = parser.build(conn.getInputStream());
    

    Hopefully this does the trick for you!

    Otherwise if this fails, it sounds like you're having to deal with URL redirects, which is a problem i used to have. You would need to do the following in that case:

     URL googleWeatherService = null;
     URLConnection conn = null;
    try {
    googleWeatherService = new URL(link);
    HttpURLConnection ucon = (HttpURLConnection) googleWeatherService.openConnection();
    ucon.setInstanceFollowRedirects(false);
    URL secondURL = new URL(ucon.getHeaderField("Location"));
    conn = secondURL.openConnection();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 
    SAXBuilder parser = new SAXBuilder();
    try {
        doc = parser.build(conn.getInputStream());
    

    Hope this solves it!

提交回复
热议问题