码迷,mamicode.com
首页 > 其他好文 > 详细

GET方式,获取服务器文件

时间:2015-10-02 08:56:56      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

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://www.dazhongtry.com/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();
        }

    }

}

 

GET方式,获取服务器文件

标签:

原文地址:http://www.cnblogs.com/zywf/p/4851886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!