Android_Okhttpファイルのアップロードとダウンロード
13634 ワード
一:okhttpを使用してファイルをダウンロードしてアップロードする
に頼る
二:MainActivityコード
三:Presenter
四:インタフェース
五:Okhttpパッケージアップロードpresenter呼び出し
に頼る
compile 'com.squareup.okhttp3:okhttp:3.9.1'
compile 'com.google.code.gson:gson:2.8.1'
アップロードダウンロードには、ネットワークとSD権限が使用されています.
二:MainActivityコード
package com.example.view;
import android.os.Environment;
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 com.example.R;
import com.example.bean.MsgBean;
import com.example.presenter.Presenter;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,IView{
private Button uploadfile;
private Button downloadfile;
private Presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// id
uploadfile = (Button)findViewById(R.id.uploadFile);
downloadfile = (Button)findViewById(R.id.downloadFile);
//
uploadfile.setOnClickListener(this);
downloadfile.setOnClickListener(this);
// presenter
presenter = new Presenter(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.uploadFile :
//
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/123.jpg");
if(file.exists()){//
Map map = new HashMap<>();
map.put("uid", "1653");
map.put("file",file);
presenter.uploadFile("http://120.27.23.105/file/upload",map);
}else{
Toast.makeText(this," ",Toast.LENGTH_SHORT).show();
}
break;
case R.id.downloadFile :
//http://g.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513d08b6a0ab376d55fbb2fbd9a3.jpg
//
String sdcardPath = Environment.getExternalStorageDirectory().getPath()+"/123.jpg";
File file2 = new File(sdcardPath);
presenter.downloadFile(file2,"http://g.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513d08b6a0ab376d55fbb2fbd9a3.jpg");
break;
}
}
@Override
public void onSuccess(Object o,int tag) {
if(tag==1){
MsgBean msg = (MsgBean) o;
Toast.makeText(this,msg.getMsg(),Toast.LENGTH_SHORT).show();
}else{
//
Toast.makeText(this,o+"",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailed(Exception e,int tag) {
Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(presenter!=null){
presenter.detatch();
}
}
}
三:Presenter
public class Presenter{
private IView iv;
public Presenter(IView iv) {
this.iv = iv;
}
public void uploadFile(String url, Map paramsMap) {
OkHttpUtils.getInstance().uploadFile(url, paramsMap, new CallBack() {
@Override
public void onSuccess(Object o) {
iv.onSuccess(o,1);
}
@Override
public void onFailed(Exception e) {
iv.onFailed(e,1);
}
});
}
public void downloadFile(File file,String url) {
OkHttpUtils.getInstance().downloadFile(file , url , new CallBack() {
@Override
public void onSuccess(Object o) {
iv.onSuccess(o,2);
}
@Override
public void onFailed(Exception e) {
iv.onFailed(e,2);
}
});
}
//
public void detatch(){
if (iv != null) {
iv = null;
}
}
}
四:インタフェース
public interface CallBack {
void onSuccess(Object o);
void onFailed(Exception e);
}
public interface CallBackPro {
void onSuccess(Object o);
void onFailed(Exception e);
void onProgressBar(Long i);//
}
五:Okhttpパッケージアップロードpresenter呼び出し
package com.example.net;
import android.os.Handler;
import com.example.bean.MsgBean;
import com.example.presenter.CallBack;
import com.example.presenter.CallBackPro;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by Administrator on 2017/12/25 0025.
*/
public class OkHttpUtils {
public static volatile OkHttpUtils instance;
Handler handler = new Handler();
private OkHttpUtils() {
}
public static OkHttpUtils getInstance() {
if (instance == null) {
synchronized (OkHttpUtils.class) {
if (instance == null) {
instance = new OkHttpUtils();
}
}
}
return instance;
}
public void uploadFile(String url, Map paramsMap, final CallBack callBack) {
MultipartBody.Builder multipartBody = new MultipartBody.Builder();
//form
multipartBody.setType(MultipartBody.FORM);
//
for (String key : paramsMap.keySet()) {
Object object = paramsMap.get(key);
if(object instanceof String){
multipartBody.addFormDataPart(key,object.toString());
}else if(object instanceof File){
File file = (File) object;
multipartBody.addFormDataPart(key,file.getName(),MultipartBody.create(MediaType.parse("multipart/form-data"),file));
}
}
RequestBody requestBody=multipartBody.build();
// Request
Request request=new Request.Builder().url(url).post(requestBody).build();
new OkHttpClient.Builder()
//
.readTimeout(100000, TimeUnit.SECONDS)
.writeTimeout(100000, TimeUnit.SECONDS)
.connectTimeout(100000, TimeUnit.SECONDS).build()
.newCall(request)
.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(e.getMessage());
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String str = response.body().string();
//
final MsgBean msgBean = new Gson().fromJson(str, MsgBean.class);
handler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(msgBean);
}
});
}
});
}
public void downloadFile(final File file, String url, final CallBackPro callBack) {
//
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdir();
}
//
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Request request=new Request.Builder().url(url).get().build();
new OkHttpClient.Builder()
.readTimeout(100000, TimeUnit.SECONDS)
.writeTimeout(100000, TimeUnit.SECONDS)
.connectTimeout(100000, TimeUnit.SECONDS).build()
.newCall(request)
.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
ResponseBody body = response.body();
//
final long totalLength = body.contentLength();
//
InputStream inputStream = body.byteStream();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int len = 0;
int num = 0;
while ((len = inputStream.read(buffer)) != -1){
num+=len;
outputStream.write(buffer,0,len);
final int finalNum = num;
handler.post(new Runnable() {
@Override
public void run() {
callBack.onProgressBar( finalNum *100/totalLength);
}
});
}
//
outputStream.flush();
outputStream.close();
inputStream.close();
handler.post(new Runnable() {
@Override
public void run() {
if(file.exists()){
//
callBack.onSuccess(file.getPath());
}
}
});
}
}
});
}
//get
public void get(String url, Map map, final CallBack callBack, final Class c){
// url
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url);
// ? if
if(stringBuffer.indexOf("?")!=-1 ){
// ? if
if(stringBuffer.indexOf("?")!=stringBuffer.length()-1){
stringBuffer.append("&");
}
}else{
stringBuffer.append("?");
}
for(Map.Entry entry:map.entrySet()){
stringBuffer.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
// & if
if(stringBuffer.indexOf("&")!=-1){
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
}
//1: OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient();
//2: Request
final Request request = new Request.Builder()
.get()
.url(stringBuffer.toString())
.build();
//3: Call
Call call = okHttpClient.newCall(request);
//4:
call.enqueue(new Callback() {
//
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(e);
}
});
}
//
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
//
final Object o = new Gson().fromJson(result, c);
// ,
handler.post(new Runnable() {
@Override
public void run() {
//
callBack.onSuccess(o);
}
});
}
});
}
}