猴王牌 2013-04-28 14:55 采纳率: 50%
浏览 479
已采纳

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条回答

  • iteye_5246 2013-04-28 15:08
    关注

    哥们送你个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]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器