zoukankan      html  css  js  c++  java
  • 抓取服务器图片下载到本地

    Sample code:
     
    import org.apache.http.Header;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
     
     
    public void download(String path, String url) {
          //  String url = "xxxxxxxx";
          //  String path = "F:/test.jpg";
            HttpClient client = null;  
            try {  
                // 创建HttpClient对象  
                client = new DefaultHttpClient();  
                // 获得HttpGet对象  
                HttpGet httpGet = getHttpGet(url, null, null);  
                // 发送请求获得返回结果  
                HttpResponse response = client.execute(httpGet);  
                // 如果成功  
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
                    byte[] result = EntityUtils.toByteArray(response.getEntity());  
                    BufferedOutputStream bw = null;  
                    try {  
                        // 创建文件对象  
                        File f = new File(path);  
                        // 创建文件路径  
                        if (!f.getParentFile().exists())  
                            f.getParentFile().mkdirs();  
                        // 写入文件  
                        bw = new BufferedOutputStream(new FileOutputStream(path));  
                        bw.write(result);  
                    } catch (Exception e) {  
                        log.error("保存文件错误,path=" + path + ",url=" + url, e);  
                    } finally {  
                        try {  
                            if (bw != null)  
                                bw.close();  
                        } catch (Exception e) {  
                            log.error(  
                                    "finally BufferedOutputStream shutdown close",  
                                    e);  
                        }  
                    }  
                }  
                // 如果失败  
                else {  
                    StringBuffer errorMsg = new StringBuffer();  
                    errorMsg.append("httpStatus:");  
                    errorMsg.append(response.getStatusLine().getStatusCode());  
                    errorMsg.append(response.getStatusLine().getReasonPhrase());  
                    errorMsg.append(", Header: ");  
                    Header[] headers = response.getAllHeaders();  
                    for (Header header : headers) {  
                        errorMsg.append(header.getName());  
                        errorMsg.append(":");  
                        errorMsg.append(header.getValue());  
                    }  
                    log.error("HttpResonse Error:" + errorMsg);  
                }  
            } catch (ClientProtocolException e) {  
                log.error("下载文件保存到本地,http连接异常,path=" + path + ",url=" + url, e);  
            } catch (IOException e) {  
                log.error("下载文件保存到本地,文件操作异常,path=" + path + ",url=" + url, e);  
            } finally {  
                try {  
                    client.getConnectionManager().shutdown();  
                } catch (Exception e) {  
                    log.error("finally HttpClient shutdown error", e);  
                }  
            }  
        }
        
        private static HttpGet getHttpGet(String url, Map<String, String> params,  
                String encode) {  
            StringBuffer buf = new StringBuffer(url);  
            if (params != null) {  
                // 地址增加?或者&  
                String flag = (url.indexOf('?') == -1) ? "?" : "&";  
                // 添加参数  
                for (String name : params.keySet()) {  
                    buf.append(flag);  
                    buf.append(name);  
                    buf.append("=");  
                    try {  
                        String param = params.get(name);  
                        if (param == null) {  
                            param = "";  
                        }  
                        buf.append(URLEncoder.encode(param, encode));  
                    } catch (UnsupportedEncodingException e) {  
                        log.error("URLEncoder Error,encode=" + encode + ",param="  
                                + params.get(name), e);  
                    }  
                    flag = "&";  
                }  
            }  
            HttpGet httpGet = new HttpGet(buf.toString());  
            return httpGet;  
        }  
  • 相关阅读:
    深入理解JavaScript系列(17):面向对象编程之概论
    深入理解JavaScript系列(16):闭包(Closures)
    深入理解JavaScript系列(15):函数(Functions)
    深入理解JavaScript系列(14):作用域链(Scope Chain)
    深入理解JavaScript系列(13):This? Yes,this!
    深入理解JavaScript系列(12):变量对象(Variable Object)
    深入理解JavaScript系列(11):执行上下文(Execution Contexts)
    深入理解JavaScript系列(10):JavaScript核心(晋级高手必读篇)
    深入理解JavaScript系列(9):根本没有“JSON对象”这回事!
    深入理解JavaScript系列(8):S.O.L.I.D五大原则之里氏替换原则LSP
  • 原文地址:https://www.cnblogs.com/mark545/p/4615654.html
Copyright © 2011-2022 走看看