【问题标题】:Retrieving a website with added user input检索添加了用户输入的网站
【发布时间】:2011-04-08 13:26:47
【问题描述】:

我读到用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 新手,如果有任何帮助,我们将不胜感激。

【问题讨论】:

  • 我记得在 Java 中可以连接两个字符串,你不能使用这种技术吗? url + inputString 变成一个新的 URL 变量,这对你有意义吗?

标签: java html html-parsing


【解决方案1】:

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

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

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

【讨论】:

  • 为快速响应干杯,我很快就会回来回答更多问题:D
【解决方案2】:
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();      

【讨论】:

  • 啊……你对我来说更明白了。你会推荐我使用哪一个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多