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

发布于 2024-10-31 08:17:51 字数 489 浏览 0 评论 0原文

我读到要在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 新手,所以有任何帮助将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

韬韬不绝 2024-11-07 08:17:51

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

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

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

You can use string concatenation like this :

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

Then you can instantiate the URL with that string.

铁憨憨 2024-11-07 08:17:51
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();      
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();      
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文