Pedro Pedro - 1 month ago 8
HTTP Question

Get the response of a HTTP GET request

I'd like to use http://www.imdbapi.com/ in Java, but I don't know I can access the http response. I tried the following:

public Map<String, String> get(String title)
{
URL url = new URL("http://www.imdbapi.com/?t=" + title);
URLConnection conn = url.openConnection();

conn.getContent();

}

Answer Source

You can use URLConnection#getInputStream():

InputStream input = conn.getInputStream();
// ...

Or just the shorthand URL#openStream() directly:

InputStream input = url.openStream();
// ...

Once having it, just send it to a JSON parser of your choice, such as for example Gson:

InputStream input = new URL("http://www.imdbapi.com/?t=" + URLEncoder.encode(title, "UTF-8")).openStream();
Map<String, String> map = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), new TypeToken<Map<String, String>>(){}.getType());
// ...

(note that I fixed your query string to be properly URL encoded)

See also: