URL中的Java变量不起作用

时间:2015-08-22 07:04:31

标签: java

所以基本上我有一个脚本可以从网站上下载一个txt文件内容。它有效,但我想在链接中添加变量,以便为每个用户自定义。所以我只想举例说:

String name = "Matt";
String URLComplete = "http://www.domain.com/" + name + "/test.txt";
URL url = new URL(URLComplete);

这不起作用,但如果我做了

URL url = new URL("http://www.domain.com/Matt/test.txt");

它会起作用,我不明白我做错了什么?

所以即使我做了以下事情:

String URLComplete = "http://www.domain.com/name/test.txt";

网址网址=新网址(URLComplete);

它不起作用,但如果我这样做

URL url = new URL("http://www.domain.com/name/test.txt");

它可以工作,我的意思是它成功地从网站读取/下载字符串/数组。我输出了两个,网址相同没有错误我通过我的浏览器访问过,最后我在最后页面。

完整代码:

这是我检索数据的完整代码。

public class Retrieve {


    public static List<String> getWhitelist()
    {
        try
        {

            String name = "Matt";
            String URLComplete = "http://www.domain.com/" + name + "/test.txt";

            List<String> strings = new ArrayList();
            URL url = new URL(URLComplete);
            BufferedReader urlReader = new BufferedReader(new InputStreamReader(url.openStream()));
            String s;
            while ((s = urlReader.readLine()) != null)
            {
                strings.add(s);
            }
            return strings;
        }
        catch (Exception e) {}
        return new ArrayList<String>();
    }


    public static String downloadString(String link)
    {
        try
        {
            URL url = new URL(link);
            BufferedReader result = new BufferedReader(new InputStreamReader(url.openStream()));
            return result.readLine();
        }
        catch (Exception e) {}
        return "Unable to connect to the internet!";
    }



}

1 个答案:

答案 0 :(得分:0)

请按照以下示例

进行尝试
    URL gamelan = new URL("http", "example.com", 80, "pages/page1.html"); 

相当于

   http://example.com:80/pages/page1.html

有关更多示例,请点击here