【问题标题】:Get the response of a HTTP GET request获取 HTTP GET 请求的响应
【发布时间】:2011-11-11 03:05:21
【问题描述】:

我想在 Java 中使用 http://www.imdbapi.com/,但我不知道我可以访问 http 响应。我尝试了以下方法:

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

    conn.getContent();      

}

【问题讨论】:

    标签: java http get


    【解决方案1】:

    你可以使用URLConnection#getInputStream():

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

    或者直接简写URL#openStream()

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

    收到后,只需将其发送至您选择的JSON parser,例如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());
    // ...
    

    (请注意,我已将您的查询字符串固定为正确的 URL 编码)

    另见:

    【讨论】:

      【解决方案2】:

      当您访问网站并输入示例电影(我做了 True Grit )时,您实际上能够看到您将得到的响应。它看起来像这样:

      {"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"}
      

      了解这些信息后,您可以轻松解析您从连接中获取的 InputStream。

      祝你好运!

      【讨论】:

        【解决方案3】:

        下面的代码应该可以帮助您入门。如果要发送特殊字符,则需要添加 URL 编码。为了解析 JSON 响应,您可能可以使用 java 中的解析器 [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】:

          我建议使用基于 apache http api 构建的 http-request

          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
          }
          

          【讨论】:

            猜你喜欢
            • 2016-09-14
            • 2021-08-28
            • 1970-01-01
            • 2017-07-14
            • 1970-01-01
            • 2014-09-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多