GET方式,获取服务器文件

本文介绍了一个使用Java实现的HTTP图片下载工具类。该工具通过发送GET请求到指定URL,读取图片流并保存到本地磁盘。代码中包含了连接超时设置、输入流读取、文件输出流写入等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,直接上代码:

package com.http.get;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Savepoint;
import java.text.DateFormat;
import java.util.Date;

public class HttpUtils {
    private static String URL_PATH="http://shuilangyizu.iask.in/TryPic/image/20150928/20150928142189698969.jpg";
    

    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
    
    public static void saveImagestodisk() throws IOException
    {
        InputStream inputStream=getInputStream();
        byte[] data=new byte[1024];
        int len=0;
        String ext=URL_PATH.substring(URL_PATH.lastIndexOf(".")).toLowerCase();
        
        
        Date date=new Date();
        
        long lSysTime1 = date.getTime() ;
        FileOutputStream fileoutputstream=new FileOutputStream("D:\\"+lSysTime1+ext);
        while((len=inputStream.read(data))!=-1)
        {
            fileoutputstream.write(data,0,len);
            
        }
        fileoutputstream.close();
        inputStream.close();
        
    }
    
    public static InputStream getInputStream() throws IOException{
        InputStream inputStream=null;
        HttpURLConnection httpurlconn=null;
        try {
            URL url=new URL(URL_PATH);
            if(url!=null)
            {
            httpurlconn=(HttpURLConnection) url.openConnection();
            //设置连接超时时间
            httpurlconn.setConnectTimeout(3000);
            //表示使用GET方式请求
            httpurlconn.setRequestMethod("GET");
            int responsecode=httpurlconn.getResponseCode();
            if(responsecode==200)
            {
                //从服务返回一个输入流
                inputStream=httpurlconn.getInputStream();
            }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;
        
        
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            saveImagestodisk();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 

转载于:https://www.cnblogs.com/shuilangyizu/p/10076608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值