美文网首页
OkHttp基础学习(三),文件下载

OkHttp基础学习(三),文件下载

作者: 英勇青铜5 | 来源:发表于2017-01-09 23:30 被阅读548次

    自己尝试使用Tomcat配合idea,写了段web代码,提供一个文件供Android客户端进行下载

    1. OkHttp下载文件

    更新下载进度

    OkHttp,真心好用,很强大

    Activity代码:

    public class DownActivity extends AppCompatActivity implements DownCallback<Integer> {
        private ProgressBar progressBar;
        private Platform mPlatform;
        private String directoryPath;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_down);
            mPlatform = Platform.get();
            init();
        }
    
        /**
         * 初始化
         */
        private void init() {
            Button button = (Button) findViewById(R.id.down_activity_bt);
            progressBar = (ProgressBar) findViewById(R.id.down_activity_pb);
            String path = Environment.getExternalStorageDirectory().getPath() + File.separator + Strings.FILE_PATH;
            File directory = new File(path);
            if (!directory.exists()) {
                boolean b = directory.mkdirs();
                if (b) ToastUtils.show(DownActivity.this, "文件夹创建成功");
            }
            directoryPath = directory.getPath();
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    down();
                }
            });
        }
    
        /**
         * 下载请求
         */
        private void down() {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(Urls.DOWN_URL)
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    sendFailResultCallback(e);
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    ResponseBody responseBody = null;
                    BufferedInputStream bis = null;
                    FileOutputStream fos = null;
                    try {
                        if (call.isCanceled()) {
                            sendFailResultCallback(new IOException("Request Canceled"));
                            return;
                        }
                        if (response.isSuccessful()) {
                            responseBody = response.body();
                            long total = responseBody.contentLength();
                            bis = new BufferedInputStream(responseBody.byteStream());
                            File file = new File(directoryPath, Strings.FILE_NAME);
                            fos = new FileOutputStream(file);
                            byte[] bytes = new byte[1024 * 8];
                            int len;
                            long current = 0;
                            while ((len = bis.read(bytes)) != -1) {
                                fos.write(bytes, 0, len);
                                fos.flush();
                                current += len;
                                //计算进度
                                int progress = (int) (100 * current / total);
                                onProgress(progress);
                            }
                        } else {
                            sendFailResultCallback(new IOException("Request Failed"));
                        }
                    } catch (Exception e) {
                        sendFailResultCallback(e);
                    } finally {
                        if (null != responseBody) {
                            responseBody.close();
                        }
                        CloseIO.close(bis);
                        CloseIO.close(fos);
                    }
                }
            });
        }
    
        /**
         * 下载失败
         */
        @Override
        public void sendFailResultCallback(final Exception e) {
            doSomething(new Runnable() {
                @Override
                public void run() {
                    String info = "Fail Message --> " + e.getMessage();
                    ToastUtils.show(DownActivity.this, info);
                }
            });
    
    
        }
    
        /**
         *  更新下载进度
         */
        @Override
        public void onProgress(final Integer integer) {
            doSomething(new Runnable() {
                @Override
                public void run() {
                    progressBar.setProgress(integer);
                }
            });
    
        }
    
        private void doSomething(Runnable runnable) {
            mPlatform.execute(runnable);
        }
    }
    

    当成功之后,利用responseBody.byteStream()得到一个InputStream,之后,只需要使用IO流将请求到的数据写入到指定的文件就可以


    2. Idea web应用

    创建一个Maven项目

    2.1 Pom.xml 配置文件

    添加必有库:

        <packaging>war</packaging>
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <kotlin.version>1.0.5</kotlin.version>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.0</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                </plugin>
               
            </plugins>
        </build>
        <dependencies>
            <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    

    2.2 在main中添加webapp

    添加webapp

    web.xml文件:

    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
             version="3.0">
        <display-name>jerk</display-name>
        
    </web-app>
    

    2.3 Tomcat配置

    • Add New Configuration中,添加Tomcat Server

      Tomcat配置
    • Server中的Application server中添加本地Tomcat路径

    • Deloyment中添加项目的导出方式为war,并将Application Context设置为项目名称

      Deloyment
    • Server中,修改On Update actionRedeployOn frame deactivationUp resources

    2.4 Servlet业务代码

    public class DownServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setHeader("Content-Disposition", "attachment;filename=a.mp4");
            String path = "/Users/g&c/Movies/17线性表12.mp4";
            File file = new File(path);
            long total = file.length();
            resp.setContentLengthLong(total);
            ServletOutputStream outputStream = resp.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024 * 8];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            fis.close();
         }
    }
    

    doGet()方法就是get请求调用的,里面读取本地文件然后输出文件流


    2.5 补充web.xml

    在web.xml中添加:

        <servlet>
            <servlet-name>android</servlet-name>
            <servlet-class>download.DownServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>android</servlet-name>
            <url-pattern>/download</url-pattern>
        </servlet-mapping>
    

    <servlet-name>中的android为随意写的名字

    完整的项目请求地址:http://192.168.0.113:8080/jerk/download

    个人ip地址+端口号+/项目名+/url-pattern


    3. 最后

    有错误请指出

    共勉 :)

    相关文章

      网友评论

          本文标题:OkHttp基础学习(三),文件下载

          本文链接:https://www.haomeiwen.com/subject/rntkbttx.html