从网络url中下载文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36125733/article/details/75452977
package com.weixinjx.util;

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

public class DownloadFromInternet {

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */  
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{  
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
                //设置超时间为3秒  
        conn.setConnectTimeout(3*1000);  
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
 
        //得到输入流  
        InputStream inputStream = conn.getInputStream();    
        //获取自己数组  
        byte[] getData = readInputStream(inputStream);      
 
        //文件保存位置  
        File saveDir = new File(savePath);  
        if(!saveDir.exists()){  
            saveDir.mkdir();  
        }  
        System.out.println(getData.toString()+"--");
        File file = new File(saveDir+File.separator+fileName);      
        FileOutputStream fos = new FileOutputStream(file);
       
        fos.write(getData);   
        if(fos!=null){  
            fos.close();    
        }  
        if(inputStream!=null){  
            inputStream.close();  
        }  
 
 
        System.out.println("info:"+url+" download success");   
 
    }  
 
 
 
    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */  
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
        byte[] buffer = new byte[1024];    
        int len = 0;    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();    
        while((len = inputStream.read(buffer)) != -1) {    
            bos.write(buffer, 0, len);    
        }    
        bos.close();    
        return bos.toByteArray();    
    }    
 
    public static void main(String[] args) {  
        try{  
            downLoadFromUrl("http://img.bimg.126.net/photo/DCi7Q__VN3NJ_63cq7sosA==/3439905690381537164.jpg",  
                    "百度.jpg","D:\\");  
        }catch (Exception e) {  
           System.out.println("失败");
        }  
    }  
}

展开阅读全文

网络上下载文件出错的简单问题!!!!

08-18

我自己写了一个方法从网上下载文件,遇到了一个问题。当我在本地的IIS测试时,下载都是很正常的。但是当我用真正的服务器上域名下载.exe时,就总是报404找不到文件错误。其实这个文件是肯定在的。用IE直接都可以下载的。但我下载网站上的about.htm又是可以的。。。。不知道这是什么问题,请高手帮帮忙。。。。谢谢了!!!rnrn本地时我直接调GetWebFile(NULL, "localhost", 80, "admin.mdb");是可以的rn但是调用GetWebFile(NULL, "www.lanz.net.cn", 80, "admin.mdb");就报404找不到文件rn而调用GetWebFile(NULL, "www.lanz.net.cn", 80, "about.htm");又是可以。rnrn///////////////////////////////////rnDWORD CWebAccess::GetWebFile(LPCTSTR pstrAgent, LPCTSTR lpstrServer, int nPort, CString strFile)rnrn CHttpConnection *pHttpConnection;rn // http file pointerrn CHttpFile *pHttpFile;rnrn DWORD dwServiceType = AFX_INET_SERVICE_HTTP;rn CString szServer, szObject;rn INTERNET_PORT Port;rn AfxParseURL(lpstrServer, dwServiceType, szServer, szObject, Port);rnrn try rn rn pHttpConnection=GetHttpConnection(szServer, INTERNET_FLAG_KEEP_CONNECTION, Port ); rnrn if( NULL == pHttpConnection)rn rn // no exception raised but there is an error. rn return WEB_ACCESS_UNEXPECTED_ERROR;rn rn rn catch (CInternetException *pException)rn rn char buffer[1023];rn pException->GetErrorMessage(buffer, 1023);rn CString resultString = buffer;rn return pException->m_dwError; rn rnrn pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, rn strFile, NULL, 1, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION); rn // pFile->AddRequestHeaders(szHeaders); rn tryrn rn pHttpFile->SendRequest(); rn rn catch(CInternetException* pEx)rn rn TCHAR szError[1024];rn pEx->GetErrorMessage(szError,1024);rn AfxMessageBox(szError);rn pHttpFile->Close();rn return FALSE;rn rnrn CString str;rn if(pHttpFile)rn rn pHttpFile->QueryInfo( HTTP_QUERY_STATUS_CODE,str);rnrn if(str=="404") /////////////这里总是返回404rn rn// m_strStatus=strFile+"不存在!";rn// UpdateData(FALSE);rn pHttpFile->Close();rn return FALSE;rn rnrn pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH,str);rn DWORD dwLen=atol(str);rn int n=strFile.ReverseFind('/');rn str=m_strAppPath+strFile.Right(strFile.GetLength()-n-1);rnrn rn CStdioFile csf;rn if(!csf.Open(str+".upg",CFile::modeCreate|CFile::modeWrite | CFile::typeBinary | CFile::shareDenyWrite))rn //先为*.upg文件rn AfxMessageBox("写文件"+str+"错误!\n文件正在使用中,请先关闭程序!",MB_ICONSTOP);rn pHttpFile->Close();rn return FALSE;rn rnrn char buf[2048];rn DWORD dwRead=0;rn while((n=pHttpFile->Read(buf,sizeof(buf)))>0)rn rn dwRead+=n;rn m_pDialog->SendMessage( WM_MYPROGPOS, 0, 100*dwRead/dwLen );rnrn MSG msg;rn for(int i=0;i<10;i++)rn rn if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))rn rn TranslateMessage(&msg);rn DispatchMessage(&msg);rn rn rn csf.Write(buf,n);rn rn pHttpFile->Close();rn rn ::DeleteFile(str);rn ::rename(str+".upg",str);rnrn return TRUE;rnrn 论坛

关于S40从网络载文件的问题

09-28

代码在S60和模拟器上运行都正常,但放在S40时,就老是系统崩溃退出了(Null Pointer java/lang/NullPointerException)rn[code=Java]rn//判断联网方式,为真时使用CMWAP代理方式rnif (Tool.isWap) rn int findIndex = url.indexOf("/", 7);rn String serverName = url.substring(7, findIndex);rn String serverPath = url.substring((findIndex + 1), url.length());rn conn = (HttpConnection) Connector.open(rn "http://10.0.0.172:80/" + serverPath,rn Connector.READ_WRITE, true);rn conn.setRequestMethod(HttpConnection.GET);rn conn.setRequestProperty("X-Online-Host", serverName);rn conn.setRequestProperty("Accept", "*/*");rnrn//使用CMNET方式联网rnelse rn conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE, true);rn conn.setRequestMethod(HttpConnection.GET);rnrnrn//使用字节流下载rnconn.setRequestProperty("Content-Type", "application/octet-stream");rn//分段下载文件rnconn.setRequestProperty("RANGE", "bytes=" + localTempFileSize + "-" + (localTempFileSize+50000));rn//添加Debug信息(可通过点击手机指定组合的按键,在手机屏幕上显示Debug信息内容)rnMainMidlet.debug.AddMsg("get response");rn//获取状态码rnint httpState = conn.getResponseCode();rnrn[/code]rnrn[color=#FF0000]rn//获取状态码——这一段老是运行不下去,每次运行到这里,软件就直接崩溃退出了(抛出的异常是:Null Pointer java/lang/NullPointerException)rnrnint httpState = conn.getResponseCode();[/color]rnrn各位老大帮忙看看是怎么回事,这个问题已经困挠我一周多了,用过其他方式来代替也是出错(用POST方式就比较正常,但是用服务器端写出字节流,客户端在接收时,在读取最后一段字节时也同样崩溃退出了,异常同上面的一样) 论坛

没有更多推荐了,返回首页