自己嘗試使用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 action為Redeploy,On frame deactivation為Up 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. 最后
有錯誤請指出
共勉 :)

