布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/upload"
android:text="上传"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/download"
android:text="下载"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/duan_upload"
android:text="继续上传"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/fen_download"
android:text="分批下载"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Main
package com.example.day1104homework;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.Util;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button upload;
private Button download;
private Button duanUpload;
private Button fenDownload;
private OkHttpClient client ;
private File file;
private long max;
private long number;
private long count;
private Handler handler = new Handler();
private String upload_url="http://192.168.43.145/hfs/";
private String get_url="http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upload = (Button) findViewById(R.id.upload);
download = (Button) findViewById(R.id.download);
duanUpload = (Button) findViewById(R.id.duan_upload);
fenDownload = (Button) findViewById(R.id.fen_download);
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request token = chain.request().newBuilder().header("token", "1231123").build();
String host = chain.request().url().host();
String s = chain.request().url().encodedPath();
Log.i(TAG, "intercept: "+host+s);
String method = chain.request().method();
Log.i(TAG, "intercept: "+method);
return chain.proceed(token);
}
};
client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(httpLoggingInterceptor)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
}
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RequestBody requestBody = RequestBody.create(MediaType.parse("media/mp4"), "/storage/emulated/0/hahah.mp4");
MultipartBody body = new MultipartBody.Builder()
.addFormDataPart("file","ludandan.mp4",requestBody)
.setType(MultipartBody.FORM)
.build();
Request request = new Request.Builder()
.post(body)
.url(upload_url)
.build();
MainActivity.this.client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Request request = new Request.Builder()
.url(get_url)
.get()
.build();
MainActivity.this.client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream("/storage/emulated/0/Movies/qazxsw.mp4");
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
fenDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Request request = new Request.Builder()
.get()
.url(get_url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
max = response.body().contentLength();
number = max/3;
fenpi();
}
});
}
});
duanUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OkHttpClient client = new OkHttpClient.Builder().build();
file = new File("/sdcard/chenjin.mp4");
final RequestBody requestBody = new RequestBody() {
@Override public @Nullable
MediaType contentType() {
return MediaType.parse("media/mp4");
}
@Override public long contentLength() {
return file.length()-10000;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
RandomAccessFile rw = new RandomAccessFile(file, "rw");
rw.seek(1500);
byte[] bytes =new byte[1024];
int len = 0;
int count = 1000;
while ((len = rw.read(bytes) )!=-1){
sink.write(bytes,0,len);
}
}
};
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file","adsjk.mp4",requestBody)
.build();
Request request = new Request.Builder()
.post(body)
.url("http://192.168.43.145/hfs/")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
});
}
private void fenpi() {
OkHttpClient client1 = new OkHttpClient.Builder().build();
final Request request = new Request.Builder()
.get()
.url(get_url)
.header("Range", "bytes = 0 - " + number)
.build();
client1.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
RandomAccessFile rw = new RandomAccessFile("/sdcard/chenjin.mp4", "rw");
rw.seek(0);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes))!=-1){
rw.write(bytes,0,len);
}
}
});
final Request request2 = new Request.Builder()
.get()
.url(get_url)
.header("Range", "bytes = "+number+" - " + number*2)
.build();
client1.newCall(request2).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
RandomAccessFile rw = new RandomAccessFile("/sdcard/chenjin.mp4", "rw");
rw.seek(number);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes))!=-1){
rw.write(bytes,0,len);
}
}
});
final Request request3 = new Request.Builder()
.get()
.url(get_url)
.header("Range", "bytes = "+number*2+" - " + max)
.build();
client1.newCall(request3).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
RandomAccessFile rw = new RandomAccessFile("/sdcard/chenjin.mp4", "rw");
rw.seek(number*2);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes))!=-1){
rw.write(bytes,0,len);
}
}
});
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
}else{
finish();
Toast.makeText(this, "未获得权限", Toast.LENGTH_SHORT).show();
}
}
}