OKHttpUtils.java 6.27 KB
package com.huaheng.mobilehuaheng.download;


import android.content.Context;
import android.os.Environment;
import android.os.Message;
import android.util.Log;

import com.huaheng.mobilehuaheng.util.ProgressCancelListener;
import com.huaheng.mobilehuaheng.util.ProgressDialogHandler;
import com.huaheng.mobilehuaheng.util.WMSLog;

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

import okhttp3.*;

/**
 * Created by youjie on 2018/4/27.
 */

public class OKHttpUtils implements ProgressCancelListener {

    private static final String TAG = "WMSlog";
    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private ProgressDialogHandler progressHandler;
    private static OKHttpUtils okHttpUtils;
    private Context mContext;

    public static OKHttpUtils as(Context context) {
        if(okHttpUtils == null) {
            okHttpUtils = new OKHttpUtils(context);
        }
        return okHttpUtils;
    }

    public OKHttpUtils(Context context) {
        mContext = context;
    }

    public void commonPost(Context context, String url, String jsonString, final OKHttpInterface okHttpInterface) {
        progressHandler = new ProgressDialogHandler(context, this, false);
        showProgressDialog();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonString);
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS).build();
        Request request= null;
        request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                WMSLog.d( "onFailure  :" + e.toString());
                dismissProgressDialog();
                okHttpInterface.onFail(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                if (cookies.size() > 0) {
                    String session = cookies.get(0);
                    String result = session.substring(0, session.indexOf(";"));
                    System.out.println( "cookies:" + result);
                }
                dismissProgressDialog();
                okHttpInterface.onSuccess(str);
                WMSLog.d("onResponse:" + str);
            }
        });
    }

    public static void get(String address, okhttp3.Callback callback)
    {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
    }

    public static void downFile(final String url, final String pkgName, final OnFileDownloadListener onFileDownloadListener) {
        final String fileName = pkgName + ".apk";
        get(url,new okhttp3.Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                onFileDownloadListener.onError(fileName, "");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;//输入流
                FileOutputStream fos = null;//输出流
                try {
                    is = response.body().byteStream();//获取输入流
                    long total = response.body().contentLength();//获取文件大小
                    if(is != null){
                        File file = new File(Environment.getExternalStorageDirectory() + "/data/",fileName);// 设置路径
                        fos = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int process = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fos.write(buf, 0, ch);
                            process += ch;
                            int show = (int)(((float)process / total) * 100);
                            onFileDownloadListener.onProgress(fileName, process);
                        }

                    }
                    fos.flush();
                    // 下载完成
                    if(fos != null){
                        fos.close();
                    }
//                    view.downSuccess();
                    onFileDownloadListener.onSuccess(fileName);
                } catch (Exception e) {
//                    view.downFial();
                    Log.d(TAG,e.toString());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                    }
                }
            }

            //private void down() {
            // progressDialog.cancel();
            // }
        });
    }

    private void showProgressDialog() {
        if (progressHandler != null) {
            progressHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (progressHandler != null) {
            progressHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            progressHandler = null;
        }
    }

    @Override
    public void onCancelProgress() {

    }
}