获取HTTP GET请求的响应

时间:2011-11-11 03:05:22

标签: java http get

我想在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();      

}

4 个答案:

答案 0 :(得分:7)

您可以使用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编码)

另见:

答案 1 :(得分:1)

当你去网站并输入样本电影(我做了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。

祝你好运!

答案 2 :(得分:1)

以下代码可以帮助您入门。如果要发送特殊字符,则需要添加URL编码。为了解析JSON响应,您可以在[link] http://www.JSON.org/

中使用java中的解析器。
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());
    }

  }
 }

答案 3 :(得分:0)

我建议使用基于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
}