java:如何获取URL查询的结果

时间:2016-07-01 17:24:31

标签: java

       URL aURL = new URL("http://stackoverflow.com/");

    System.out.println("protocol = " + aURL.getProtocol());
    System.out.println("authority = " + aURL.getAuthority());
    System.out.println("host = " + aURL.getHost());
    System.out.println("port = " + aURL.getPort());
    System.out.println("path = " + aURL.getPath());
    System.out.println("query = " + aURL.getQuery());
    System.out.println("filename = " + aURL.getFile());
    System.out.println("ref = " + aURL.getRef());

上面的代码显示了URL的一些属性,但是我需要知道的是,如果有一种方法可以获得在URL中执行的查询结果,我有一个用于测试目的的网站,我正在通过url(主要是SELECTs)并在网页的html中显示结果,我想知道是否已经有一个获取特定SELECT结果的函数,到目前为止我做了一个方法将页面的html下载到.txt,对内容进行排序然后获取查询结果,但这不是很实用。 -Regards

1 个答案:

答案 0 :(得分:0)

显然,一个简单的工作就可以完成。 资料来源:http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

    private void sendGet() throws Exception {

    String url = "your url here";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString());

}