How to connect to TMDB api

Jusleong picture Jusleong · Oct 18, 2013 · Viewed 11.6k times · Source

Here is my api key: 7b5e30851a9285340e78c201c4e4ab99

And I am trying to connect to TMDB api: here is my code:

package movieDBapiconnnection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class connection {

    public static void main(String[] args) throws Exception{
            URL url = new URL("http://api.themoviedb.org/3/movie/550?api_key=7b5e30851a9285340e78c201c4e4ab99/3/movie/550");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type", "application/json");

            BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
    }
}

But it always showing me the error that:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: http://api.themoviedb.org/3/movie/550?api_key=7b5e30851a9285340e78c201c4e4ab99/3/movie/550 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at movieDBapiconnnection.connection.main(connection.java:17)

Answer

Mike Marks picture Mike Marks · Jan 21, 2014

First, I would use a TMDB wrapper. Get a Java wrapper at: https://github.com/Omertron/api-themoviedb. Use the fully tested and tried wrapper rather than trying to connect to it and creating your models from scratch. Typically in a wrapper when you instantiate a class, you pass in the API key into the constructor and the wrapper does the rest.