获取HTTP GET请求的响应 [英] Get the response of a HTTP GET request

查看:127
本文介绍了获取HTTP GET请求的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}


推荐答案

使用 URLConnection#getInputStream()
$ b

You can use URLConnection#getInputStream():

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

或者只是简写 URL#openStream()

Or just the shorthand URL#openStream() directly:

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

只要将它发送给您选择的JSON解析器,例如 Gson

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

(注意我将您的查询字符串修改为正确的URL编码)


  • <一个href =https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests>使用java.net.URLConnection来触发和处理HTTP请求

  • 将JSON转换为Java

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

这篇关于获取HTTP GET请求的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆