爱程序网

抓取服务器图片下载到本地

来源: 阅读:

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

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助