改变世界的是这样一群人,他们寻找梦想中的乐园,当他们找不到时,他们亲手创造了它

GET方式,获取服务器文件

话不多说,直接上代码:

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();
        }

    }

}

 

posted @ 2018-12-06 14:40  水狼一族  阅读(2301)  评论(0编辑  收藏  举报
改变世界的是这样一群人,他们寻找梦想中的乐园,当他们找不到时,他们亲手创造了它