Android–okhttp與php互動,檔案上傳下載

sealin發表於2017-09-07
版權宣告:本文為博主原創文章,轉載請標明出處。 https://blog.csdn.net/chaoyu168/article/details/77880320

okhttp配置:

okhttp的下載地址:http://square.github.io/okhttp/

okio的下載地址: https://github.com/square/okio

兩個jar包匯入到工程中,放在libs目錄下,右鍵點選jar包,選擇Add As Library就行了,兩個包都要新增。

import java.io.FileOutputStream;
    import java.io.IOException;

    import android.Manifest;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.concurrent.TimeUnit;

    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.ResponseBody;
    import okio.Buffer;
    import okio.BufferedSink;
    import okio.BufferedSource;
    import okio.ForwardingSink;
    import okio.ForwardingSource;
    import okio.Okio;
    import okio.Sink;
    import okio.Source;

    public class MainActivity extends AppCompatActivity {

        private OkHttpClient okHttpClient;
        private TextView textView;
        private File tempFile;
        private File targetFile;
        private String path;
        private Button button1;
        private Button button2;
        private Button button3;
        private Button button4;
        //private long time;

        private static final int REQUEST_EXTERNAL_STORAGE = 1;
        private static final int FILE_SELECT_CODE = 1;
        private static String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setTitle("上傳檔案並顯示進度");
            //verifyStoragePermissions(MainActivity.this);

            textView = (TextView) findViewById(R.id.tv1);
            button1 = (Button) findViewById(R.id.btn_choose);
            button2 = (Button) findViewById(R.id.btn_upload);
            button3 = (Button) findViewById(R.id.btn_download);
            button4 = (Button) findViewById(R.id.btn_display);
            path = "";

            okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(120, TimeUnit.SECONDS)
                    .build();

            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showFileChooser();
                }
            });

            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startUploadClick();
                }
            });

            button3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startDownloadClick();
                }
            });

            button4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this,DisplayActivity.class);
                    startActivity(intent);
                }
            });
        }

                //開啟檔案選擇器
        private void showFileChooser() {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

            try {
                startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(this, "Please install a File Manager.",  Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)  {
            switch (requestCode) {
                case FILE_SELECT_CODE:
                    if (resultCode == RESULT_OK) {
                        // Get the Uri of the selected file
                        Uri uri = data.getData();
                        path = FileUtils.getPath(this, uri);
                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

        public String getFileName(String pathandname){

            int start=pathandname.lastIndexOf("/");
            //int end=pathandname.lastIndexOf("");
            if(start!=-1 ){
                return pathandname.substring(start+1);
            }else{
                return null;
            }

        }

        //點選按鈕開始上傳檔案
        public void startUploadClick() {
            //tempFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test1.txt");
            //showFileChooser();
            String fileName = "";
            tempFile = new File(path);
            //tempFile = new File("/data/data/upload/man.jpg");

            if (tempFile.getName() == null){
                Toast.makeText(MainActivity.this, "找不到該檔案!", Toast.LENGTH_SHORT).show();
            }
            else {
                fileName = getFileName(path);
            }

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("image/jpg"), tempFile))
                    .build();
            //ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, progressListener);
            Request request = new Request.Builder()
                    .url("http://xxx.xxx.xxx.xx/receive_file.php")
                    .post(requestBody)
                    .build();
            //上面url中的內容請改成自己php檔案的所在地址
            okHttpClient.newCall(request).enqueue(callback_upload);


        }

        //點選按鈕開始下載檔案
        public void startDownloadClick() {

            targetFile = new File("/data/data/com.example.ywy.mycloud1/cache/"  + "test1.jpg");

            Request request = new Request.Builder()
                    .url("http://xxx.xxx.xxx.xx/downloads/woman.jpg")
                    .build();
            okHttpClient.newCall(request).enqueue(callback_download);
            //上面url中的內容請改成自己想要下載的檔案的所在地址
        }

        //上傳請求後的回撥方法
        private Callback callback_upload = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                setResult(e.getMessage(), false);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                setResult(response.body().string(), true);
            }
        };

        private  Callback callback_download = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                setResult(e.getMessage(),false);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response != null) {
                    //下載完成,儲存資料到檔案
                    //verifyStoragePermissions(MainActivity.this);
                    InputStream is = response.body().byteStream();
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    byte[] buf = new byte[1024];
                    int hasRead = 0;
                    while((hasRead = is.read(buf)) > 0) {
                        fos.write(buf, 0, hasRead);
                    }
                    fos.close();
                    is.close();
                    setResult("下載成功", true);
                }
            }
        };

        //顯示請求返回的結果
        private void setResult(final String msg, final boolean success) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (success) {
                        Toast.makeText(MainActivity.this, "請求成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "請求失敗", Toast.LENGTH_SHORT).show();
                    }
                    textView.setText(msg);
                }
            });
        }

}

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

/**
 * Created by YWY on 2016/11/9.
 */
public class FileUtils {

    public static String getPath(Context context, Uri uri) {

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection,null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        }

        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
}

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class DisplayActivity extends AppCompatActivity {

    private  ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);

        imageView = (ImageView)findViewById(R.id.iv);
        Bitmap bitmap = BitmapFactory.decodeFile("/data/data/com.example.ywy.mycloud1/cache/test1.jpg");
        imageView.setImageBitmap(bitmap);

    }
}

許可權:

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
PHP:
<?php
$base_path = "./text/"; //存放目錄
if(!is_dir($base_path)){
    mkdir($base_path,0777,true);
}
$target_path = $base_path . basename ( $_FILES [`file`] [`name`] );
if (move_uploaded_file ( $_FILES [`file`] [`tmp_name`], $target_path )) {
  $array = array (
      "status" => true,
      "msg" => $_FILES [`file`] [`name`] 
  );
  echo json_encode ( $array );
} else {
  $array = array (
      "status" => false,
      "msg" => "There was an error uploading the file, please try again!" . $_FILES [`file`] [`error`] 
  );
  echo json_encode ( $array );
}
?>















相關文章