Reputation: 676
Sorry for the very basic question, I am new to Java. To get data from an URL I use code like this
URL url = new URL(BaseURL+"login?name=foo");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
while ((inputLine = in.readLine()) != null)
...
That works perfectly fine. When I now want to continue and send the next command to the server (like ".../getStatus"), do I need to create these objects over and over again, or is there a smarter way?
Thanks!
Upvotes: 1
Views: 115
Reputation: 676
I looked into the Apache HttpComponents (HttpClient) and it still requires a lot of code. As I don't need cookie-handling (it's only a simple RESTful server giving json-blocks as responses) I'm going for a very simple solution:
public static String readStringFromURL(String requestURL) throws IOException
{
URL u = new URL(requestURL);
try (InputStream in = u.openStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
For me that looks like a perfect solution, but as mentioned, I am new to Java and open (and thankful) for hints...
Upvotes: 0
Reputation: 5449
You have to call openConnection
again in order to get a new URLConnection
. The HttpURLConnection does internal caching, though, so if the HTTP-server supports Connection: keep-alive
the underlying connection to the server will be reused so it's not that bad as it originally might look. It's just hidden from you.
Upvotes: 2