简体   繁体   English

如何使用Java从服务器端的特定URL获取HTML内容?

[英]How can I get HTML content from a specific URL on server side by using Java?

I am designing an application that needs to load HTML content from a specific URL on server side by using Java. 我正在设计一个应用程序,该应用程序需要使用Java从服务器端的特定URL加载HTML内容。 How can I solve it? 我该如何解决?

Regards, 问候,

I have used the Apache Commons HttpClient library to do this. 我已经使用Apache Commons HttpClient库来做到这一点。 Have a look here: http://hc.apache.org/httpclient-3.x/tutorial.html 在这里看看: http : //hc.apache.org/httpclient-3.x/tutorial.html

It is more feature rich than the JDK HTTP client support. 它比JDK HTTP客户端支持功能更丰富。

If all you need is read the url you do not need to resort to third party libraries, java has built in support to retrieve urls. 如果您只需要阅读url,就无需诉诸第三方库,则java内置了对检索url的支持。


import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

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

If it was php, you could use cURL , but since it's java, you would use HttpURLConnection , as I just found out on this question: 如果它是php,则可以使用cURL ,但是由于它是java,因此可以使用HttpURLConnection ,正如我在这个问题上发现的那样:

cURL equivalent in JAVA 相当于JAVA中的cURL

import java.io.BufferedReader; 导入java.io.BufferedReader; import java.io.IOException; 导入java.io.IOException; import java.io.InputStreamReader; 导入java.io.InputStreamReader; import java.net.MalformedURLException; 导入java.net.MalformedURLException; import java.net.URL; 导入java.net.URL; import java.net.URLConnection; 导入java.net.URLConnection;

public class URLConetent{ public static void main(String[] args) { 公共类URLConetent {公共静态void main(String [] args){

    URL url;

    try {
        // get URL content

        String a="http://localhost:8080//TestWeb/index.jsp";
        url = new URL(a);
        URLConnection conn = url.openConnection();

        // open the stream and put it into BufferedReader
        BufferedReader br = new BufferedReader(
                           new InputStreamReader(conn.getInputStream()));

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
                System.out.println(inputLine);
        }
        br.close();

        System.out.println("Done");

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM