在java中打开另一个http连接

时间:2013-06-18 04:46:58

标签: java

我尝试连接到某个网站,从中获取一些网址,然后连接到这些网址,获取一些信息。这是我的代码。

    URL url = new URL("http://www.nchmf.gov.vn/web/vi-VN/62/23/44/map/Default.aspx");
    URLConnection con = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    String l;
    String Area;

    Pattern Province = Pattern.compile("Thị xã/T.Phố :");
    Pattern City = Pattern.compile("<option(.*?)ue=\"(.*?)\">(.*?)</option>");


    while ((l=in.readLine())!=null) {
        Matcher ProvinceFound = Province.matcher(l);
        if (ProvinceFound.find()) {
            while((l=in.readLine())!=null
                  && !l.contains("</select></span>")){
                Matcher CityCode = City.matcher(l);
                if(CityCode.find()){
                    if(!"0".equals(CityCode.group(2))){
                        URL url1 = new URL("http://www.nchmf.gov.vn/web/vi-VN/62/23/44/map/Default.aspx");
                        URLConnection con1 = url1.openConnection();
                        BufferedReader in1 = new BufferedReader(new InputStreamReader(con1.getInputStream()));

                        while((Area=in1.readLine())!=null){
                            System.out.println(Area);
                            break;
                        }
                    }

                }
            }
        }
    }
} 

我得到的结果只不过是空行。如果我输入“System.out.println(l);”它仍会打印一些东西。在第一个连接上,所以我认为问题是第二个连接。

任何人都可以告诉我代码中有什么问题,非常感谢。

1 个答案:

答案 0 :(得分:0)

我猜你无法从第二个网址读取,因为你在第一个网址上阻止了。两个建议:

  1. 为您要阅读的每个新网址开始一个新主题
  2. 读取第一个URL中的所有数据,并将要处理的链接添加到List。然后,当您阅读完主URL后,您可以一次阅读其他每个URL。