开发者

Retrieving a website with added user input

开发者 https://www.devze.com 2023-02-22 20:28 出处:网络
I read that to retrieve a webpage in java, it is quick to use: URL url = new URL(\"开发者_运维技巧http://example.com\");

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号