检索添加了用户输入的网站

时间:2011-04-08 13:26:48

标签: java html html-parsing

我读到要在java中检索网页,可以快速使用:

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

但是我如何将用户提供的变量添加到url中?例如:

用户输入x 加载页面http://example.com/x.php

我是java的新手,所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

您可以像这样使用字符串连接:

final String url = "http://example.com" + "/" + userInput

然后,您可以使用该字符串实例化URL。

答案 1 :(得分:0)

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

或者

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