首页 > Web开发 > 详细

HttpURL

时间:2016-03-04 22:31:27      阅读:242      评论:0      收藏:0      [点我收藏+]

* 步骤:
    1. new一个URL对象
    2. new一个HttpURLConnection对象
    3. connection连接
    4. getResponseCode()
    5. 读取流

            // 将网址封装为URL对象
            URL url = new URL(path);
            // 用url里面的openConnection方法打开连接。
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            // 设置HttpURLConnection一些属性。
            // 1:设置请求方式。--默认为 get
            connection.setRequestMethod("GET");
            // 2:设置连接时间。--可写不可写
            connection.setConnectTimeout(5000);
            // 3:设置可读。---可写可不写。默认为true
            connection.setDoInput(true);
            // 4:设置可以往服务器端写入数据------可写可不写。默认为false
            connection.setDoOutput(true);    
            // 连接
            connection.connect();
            // 服务器端接收到客户端的请求,并返回响应码。
            int code = connection.getResponseCode();
            if (code == 200) {
                // 读取服务器端发送过来的数据。
                InputStream is = connection.getInputStream();
                FileOutputStream fos = new FileOutputStream("f:\\logo2.jpeg");
                byte[] b = new byte[1024];
                int length = -1;
                while ((length = is.read(b)) != -1) {
                    fos.write(b, 0, length);
                }
                is.close();
                fos.close();
            }

 

HttpURL

原文:http://www.cnblogs.com/anni-qianqian/p/5243459.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!