详解GET方法:HttpURLConnection从网络获取资源

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**

 * 客户端程序:用于根据指定的网址。访问网络的数据

    // 拿获取百度服务器端的logo图片为例

 *
 * @author Administrator
 *
 */
public class Demo01_HttpURLConnection {

    public static void main(String[] args) {
        FileOutputStream fos = null;
     
        // step1:先获取网络地址

        String baseUrl = "https://www.baidu.com/img/bd_logo1.png";
        // step2:根据网址,构建URL对象。用于打开和该网址指向的资源,建立连接
        try {
            URL url = new URL(baseUrl);
            // step3:根据url,打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // step4:设置本次网络请求的参数
            // 设置请求方式
            connection.setRequestMethod("GET");// 该方法的参数:所有的参数字母全部大写。
            // 设置连接超时
            connection.setConnectTimeout(5000);
            // step5:开始连接
            connection.connect();// 该行代码可以省略
            // step6:获取服务端的响应码
            int responseCode = connection.getResponseCode();
            System.out.println(responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {// 200
                // step7:获取流,读数据
                InputStream inputStream = connection.getInputStream();
                String fileName = baseUrl.substring(baseUrl.lastIndexOf("/") + 1);
                File file = new File("D:\\Ruby\\pro", fileName);
                fos = new FileOutputStream(file);
                byte[] bs = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bs)) != -1) {
                    fos.write(bs, 0, len);
                }
                System.out.println("图片下载完毕。。。");
            }

            // connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
  
    }

}

GitHub:  https://github.com/HuaDanJson
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张海龙_China

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值