Retrieving a website with added user input
I read that to retrieve a webpage in java, it is quick to use:
URL url = new URL("开发者_运维技巧http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
// read the contents using an InputStreamReader
But how would I add a variable given by the user into the url? For example:
User inputs x Loads page http://example.com/x.php
I'm new to java, so any help would be appreciated.
You can use string concatenation like this :
final String url = "http://example.com" + "/" + userInput
Then you can instantiate the URL with that string.
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
URL urlWithInput = new URL("http://example.com" + input);
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
Or
String url = "http://example.com" + "/" + input
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
URL urlWithInput = new URL(url);
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
精彩评论