Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a 403 error when I try open a URL

Tags:

java

imdb

api

I am currently using the imdb api from http://imdbapi.org to get some information about a movie. When I use the API and try to open this url in java it gives me a 403 error. The url is supposed to return the data in JSON. Here is my code so far(Java 7):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class Test {
    public static void main(String[] args) {
        URL url =null;
        try {
            url = new URL("http://imdbapi.org/?q=batman");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        InputStream is =null;
        try {
            is = url.openConnection().getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader reader = new BufferedReader( new InputStreamReader( is )  );
        String line = null;
        try {
            while( ( line = reader.readLine() ) != null )  {
               System.out.println(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(line);
    }
}
like image 785
parasm Avatar asked May 30 '13 01:05

parasm


1 Answers

You should set User-Agent:

System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36"); 

or

URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
is = connection.getInputStream();
like image 114
Jarandinor Avatar answered Sep 18 '22 17:09

Jarandinor