Pedro Pedro - 5 months ago 40
HTTP Question

Get the response of a HTTP GET request

I'd like to use 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("" + title);
URLConnection conn = url.openConnection();



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("" + 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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download