HttpURLConnection 抓去页面 返回始终是 Null

[code="java"]

package util;

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

import sun.net.www.protocol.http.HttpURLConnection;

public class TestURL {

public static void main(String[] args) {
    try {
        URL url = new URL("http://www.baidu.com");
        HttpURLConnection urlc =(HttpURLConnection) url.openConnection();
        //urlc.getContent();
        urlc.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream(),"UTF-8"));
        StringBuffer sb = new StringBuffer();
        while (br.readLine() != null) {
            sb.append(br.readLine());
        }
        System.out.println(sb.toString());
        br.close();
        urlc.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

[/code]

1个回答

哥们送你个demo,你慢慢看吧,貌似你:
构建
[code="java"]BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream(),"UTF-8")); [/code]
的时候应该这样:
[code="java"]reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(),"UTF-8")); [/code]

下面是demo:
[code="java"]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class TestUrlConnection {

public static void main(String[] args) {
    BufferedReader reader = null;
    HttpURLConnection connection = null;
    try {
        // 新建一个URL对象,指定到请求的url.
        URL url = new URL("http://www.baidu.com");
        connection = (HttpURLConnection) url.openConnection();

        reader = new BufferedReader(new InputStreamReader(connection
                .getInputStream(),"UTF-8")); 
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
    }
}

}
[/code]

dbh0512
猴王牌 while ((line = reader.readLine()) != null) { System.out.println(line); }
7 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐