OkHttp基礎(chǔ)學(xué)習(xí)(三),文件下載

自己嘗試使用Tomcat配合idea,寫了段web代碼,提供一個文件供Android客戶端進(jìn)行下載

1. OkHttp下載文件

更新下載進(jìn)度

OkHttp,真心好用,很強(qiáng)大

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, "文件夾創(chuàng)建成功");
        }
        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;
                            //計算進(jìn)度
                            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);
            }
        });


    }

    /**
     *  更新下載進(jìn)度
     */
    @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);
    }
}

當(dāng)成功之后,利用responseBody.byteStream()得到一個InputStream,之后,只需要使用IO流將請求到的數(shù)據(jù)寫入到指定的文件就可以


2. Idea web應(yīng)用

創(chuàng)建一個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中添加項目的導(dǎo)出方式為war,并將Application Context設(shè)置為項目名稱

    Deloyment

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

2.4 Servlet業(yè)務(wù)代碼

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請求調(diào)用的,里面讀取本地文件然后輸出文件流


2.5 補(bǔ)充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. 最后

有錯誤請指出

共勉 :)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,715評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,290評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,366評論 25 708
  • 終于把我趕出了你的生活 我只是覺得就我一個人心甘情愿,犯賤犯到自己都煩自己,可是你都無動于衷,這樣好可笑,明明你都...
    灰灰_ab65閱讀 361評論 0 2
  • 【今日之最】 2017年倒計時100天拉開序幕啦 【今日很特別】 麻麻生日 秋分日 倒計時100天 【晨間計劃-朝...
    差不多小姐少女薇閱讀 232評論 1 0

友情鏈接更多精彩內(nèi)容