Java HttpURLConnection 仅适用于某些站点

Java HttpURLConnection only works on certain sites

package internet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class internet {
   public static void main(String[] args) {
    try {
        URL url = new URL("http://www.wikipedia.org");

        HttpURLConnection hc = (HttpURLConnection) url.openConnection();
        int length = hc.getContentLength();
        System.out.println(length);
        InputStream input = url.openStream();
        byte[] binput = new byte[100000];
        input.read(binput);
        input.close();

        final String result = new String(binput);

        System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

奇怪的事情发生了。我无法显示结果,长度为 -1。但是当我使用其他 url 时。例如,http://www.edwinlengzai.com。有用。有什么想法吗?

你可以这样试试吗?地址应该设置为你想阅读的站点

    URL page = new URL(address);
    StringBuffer text = new StringBuffer();
    HttpURLConnection conn = (HttpURLConnection) page.openConnection();
    conn.connect();
    InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
    BufferedReader buff = new BufferedReader(in);
    box.setText("Getting data ...");
    String line;
    do {
      line = buff.readLine();
      text.append(line + "\n");
    } while (line != null);
    final String result = new String(text.toString());