Get the response of a HTTP GET request

2019-05-29 04:29发布

问题:

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();      

}

回答1:

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:

  • Using java.net.URLConnection to fire and handle HTTP requests
  • Converting JSON to Java


回答2:

When you go the website and type in the sample movie (i did True Grit ) you are actually able to see the response you would be getting. It looks something like this:

{"Title":"True Grit","Year":"2010","Rated":"PG-13","Released":"22 Dec 2010","Genre":"Adventure, Drama, Western","Director":"Ethan Coen, Joel Coen","Writer":"Joel Coen, Ethan Coen","Actors":"Jeff Bridges, Matt Damon, Hailee Steinfeld, Josh Brolin","Plot":"A tough U.S. Marshal helps a stubborn young woman track down her father's murderer.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjIxNjAzODQ0N15BMl5BanBnXkFtZTcwODY2MjMyNA@@._V1._SX320.jpg","Runtime":"1 hr 50 mins","Rating":"8.0","Votes":"51631","ID":"tt1403865","Response":"True"}

After knowing this info, you can easily parse your InputStream, which you obtain from your connection.

Good luck!



回答3:

The below code should get you started. You need to add URL encoding if you are going to send special characters. In-order to parse JSON response you could probably use parser available in java at [link] http://www.JSON.org/

package problem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class Test {

public static void main(String args[])
{
 BufferedReader rd;
 OutputStreamWriter wr;

try
{
    URL url = new URL("http://www.imdbapi.com/?i=&t=dexter");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    wr = new OutputStreamWriter(conn.getOutputStream());
    wr.flush();

    // Get the response
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
       System.out.println(line);
    }
}
catch (Exception e) {
        System.out.println(e.toString());
    }

  }
 }


回答4:

I recomend use http-request built on apache http api.

private static final HttpRequest<Map<String, String>> HTTP_REQUEST = 
        HttpRequestBuilder.createGet("http://www.imdbapi.com/", 
             new TypeReference<Map<String, String>>{}
        ).build();

public Map<String, String> get(String title) {
   ResponseHandler<Map<String, String>> responseHandler = HTTP_REQUEST.execute("t", title);
   return responseHandler.orElse(Collections.emptyMap()); //returns response parsed as map or empty map when response body is empty
}


标签: java http get