2

我正在尝试以 html 格式获取和下载文件。以下是代码块:

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

public class URLReader {

    public static void main(String[] args) throws Exception {

    System.setProperty("http.proxyHost", "webcache.mydomain.com");
    System.setProperty("http.proxyPort", "8080");

    URL url = new URL("http://www.java2s.com/");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

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

在这里,当我尝试运行此 java 文件时,它显示以下错误:

D:\Build>javac URLReader.java

D:\Build>java URLReader

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:523)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:227)
    at sun.net.www.http.HttpClient.New(HttpClient.java:300)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:977)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:925)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
    at java.net.URL.openStream(URL.java:1010)
    at URLReader.main(URLReader.java:12)

我认为代码没有任何问题,因为当我尝试在家中运行此代码时,它对我有用。但是当我在我的办公室尝试它时,它向我显示了错误!所以我想我的办公室一定有某种堵塞。

我可以在代码中设置任何代理以便它可以工作吗?

4

2 回答 2

4

如果您在代理后面,则需要配置Java以使用它。阅读此处了解如何为您的网络程序设置代理

于 2013-05-28T05:33:07.550 回答
1

试试这个链接中提到的http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

//Set the http proxy to webcache.mydomain.com:8080

System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setPropery("http.proxyPort", "8080");

// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);

// From now on http connections will be done directly.
于 2013-05-28T05:35:22.410 回答