JAXB - unmarshalling from url

前端 未结 1 1666
一生所求
一生所求 2021-01-13 08:20

I\'m tryting to display title and id of game from this site: http://thegamesdb.net/api/GetGame.php?id=2

When I was unmarshalling from this url: http://www.w3schools.

相关标签:
1条回答
  • 2021-01-13 08:46

    The only thing that is wrong with your annotation is

    public class Game {
      private int id;
      @XmlElement(name = "GameTitle") //You need to add this since first letter is uppercase, otherwise the GameTitle will not unmarshall.
      private String gameTitle; 
      ... your code ...
    }
    

    So why is it not the rest working?

    Server returned HTTP response code: 403 for URL: http://thegamesdb.net/api/GetGame.php?id=2

    403 = Forbidden

    Solution (make the server believe you are a browser)

    URL url = new URL("http://thegamesdb.net/api/GetGame.php?id=2");
    HttpURLConnection http = (HttpURLConnection) url.openConnection(); 
    http.addRequestProperty("User-Agent", "Mozilla/4.76"); 
    InputStream is = http.getInputStream();
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    customer = (Data) jaxbUnmarshaller.unmarshal(is);
    List<Game> games = customer.getGames();
    game = games.get(0);
    

    Note: Try catch final, close streams and checking for NullPointer is beyond this example and up to user.

    0 讨论(0)
提交回复
热议问题