java 获取网络servelt 返回下载文件大小

public  long getFileSize(String sURL) { 
        int nFileLength = -1; 
        try { 
            URL url = new URL(sURL); 
            HttpURLConnection httpConnection = (HttpURLConnection) url 
            .openConnection(); 
            httpConnection.setRequestProperty("User-Agent", "Internet Explorer"); 
            int responseCode = httpConnection.getResponseCode(); 
            if (responseCode >= 400) { 
                System.err.println("Error Code : " + responseCode); 
                return -2; // -2 represent access is error 
            } 
            String sHeader; 
            for (int i = 1;; i++) { 
                sHeader = httpConnection.getHeaderFieldKey(i); 
                if(null != sHeader){
                    
                    System.out.println(sHeader);
                }
                if (sHeader != null) { 
                    if (sHeader.equals("Content-Length")) { 
                        nFileLength = Integer.parseInt(httpConnection 
                                .getHeaderField(sHeader)); 
                        break; 
                    } 
                } else 
                    break; 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        System.out.println(nFileLength); 
        return nFileLength; 
    } 

 

posted @ 2013-01-15 09:57  镇水古月  阅读(495)  评论(0编辑  收藏  举报