我正在设计一个需要使用Java从服务器端的特定URL加载HTML内容的应用程序。我该如何解决?

此致

有帮助吗?

解决方案

我已经使用Apache Commons HttpClient库来执行此操作。看看这里: http://hc.apache.org/httpclient-3.x/tutorial。 HTML

它比JDK HTTP客户端支持功能更丰富。

其他提示

如果你需要的只是阅读网址,你不需要求助于第三方库,java已经内置支持来检索网址。


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

如果是php,你可以使用 cURL ,但由于它是java,你会使用 HttpURLConnection ,正如我刚刚发现的那样这个问题:

JAVA中的cURL等效内容

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

public class URLConetent {     public static 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归因
不隶属于 StackOverflow
scroll top