OKHTTP

来源:互联网 发布:java 运行时获取注解 编辑:程序博客网 时间:2024/06/05 11:22

MainActivity类

package com.bwie.asus.okhttp;import android.content.Intent;import android.database.Cursor;import android.graphics.Bitmap;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.TextView;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLDecoder;import java.util.concurrent.TimeUnit;import okhttp3.Cache;import okhttp3.CacheControl;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;public class MainActivity extends AppCompatActivity {    private TextView tv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //       tv = (TextView) findViewById(R.id.tv);        findViewById(R.id.photo).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                toPhoto();            }        });        findViewById(R.id.camear).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                toCamera();            }        });        cache();//        new Thread(new Runnable() {//            @Override//            public void run() {//                a();//            }//        }).start();        //       b();    }    private void a() {        try {            OkHttpClient client = new OkHttpClient();            Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build();            Call call = client.newCall(request);            Response response = call.execute();            if (response.isSuccessful()) {                final String string = response.body().string();                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        tv.setText(string);                    }                });            }        } catch (IOException e) {            e.printStackTrace();        }    }    private void b() {        try {            OkHttpClient client = new OkHttpClient();            Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();            Call call = client.newCall(request);            call.enqueue(new Callback() {                @Override                public void onFailure(Call call, IOException e) {                }                @Override                public void onResponse(Call call, Response response) throws IOException {                    final String string = response.body().string();                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            tv.setText(string);                        }                    });                }            });        } catch (Exception e) {            e.printStackTrace();        }    }    public static final MediaType MEDIA_TYPE_MARKDOWN            = MediaType.parse("text/x-markdown; charset=utf-8");    public void postFile(File file) {        String path = file.getAbsolutePath();        String[] split = path.split("\\/");        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");        OkHttpClient client = new OkHttpClient();        RequestBody requestBody = new MultipartBody.Builder()                .setType(MultipartBody.FORM)                .addFormDataPart("imageFileName", split[split.length - 1])                .addFormDataPart("image", split[split.length - 1], RequestBody.create(MEDIA_TYPE_PNG, file))                .build();        Request request = new Request.Builder().post(requestBody).url("http://qhb.2dyt.com/Bwei/upload").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 {                System.out.println("response = " + response.body().string());            }        });    }    static final int INTENTFORCAMERA = 1 ;    static final int INTENTFORPHOTO = 2 ;    public String LocalPhotoName;    public String createLocalPhotoName() {        LocalPhotoName = System.currentTimeMillis() + "face.jpg";        return  LocalPhotoName ;    }    public void toCamera(){        try {            Intent intentNow = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);            Uri uri = null ;//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//                uri = FileProvider.getUriForFile(UploadPhotoActivity.this, "com.bw.dliao", SDCardUtils.getMyFaceFile(createLocalPhotoName()));//            }else {//                uri = Uri.fromFile(Utils.getMyFaceFile(createLocalPhotoName())) ;//            }            intentNow.putExtra(MediaStore.EXTRA_OUTPUT, uri);            startActivityForResult(intentNow, INTENTFORCAMERA);        } catch (Exception e) {            e.printStackTrace();        }    }    public void toPhoto(){        try {            createLocalPhotoName();            Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);            getAlbum.setType("image/*");            startActivityForResult(getAlbum, INTENTFORPHOTO);        } catch (Exception e) {            e.printStackTrace();        }    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        switch (requestCode) {            case INTENTFORPHOTO:                try {                    Uri originalUri = data.getData();                    File f = null;                    if (originalUri != null) {                        f = new File(Utils.photoCacheDir, LocalPhotoName);                        String[] proj = {MediaStore.Images.Media.DATA};                        Cursor actualimagecursor =  this.getContentResolver().query(originalUri, proj, null, null, null);                        if (null == actualimagecursor) {                            if (originalUri.toString().startsWith("file:")) {                                File file = new File(originalUri.toString().substring(7, originalUri.toString().length()));                                if(!file.exists()){                                    originalUri = Uri.parse(URLDecoder.decode(originalUri.toString(),"UTF-8"));                                    file = new File(originalUri.toString().substring(7, originalUri.toString().length()));                                }                                FileInputStream inputStream = new FileInputStream(file);                                FileOutputStream outputStream = new FileOutputStream(f);                                copyStream(inputStream, outputStream);                            }                        } else {                            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);                            actualimagecursor.moveToFirst();                            String img_path = actualimagecursor.getString(actual_image_column_index);                            if (img_path == null) {                                InputStream inputStream = this.getContentResolver().openInputStream(originalUri);                                FileOutputStream outputStream = new FileOutputStream(f);                                copyStream(inputStream, outputStream);                            } else {                                File file = new File(img_path);                                FileInputStream inputStream = new FileInputStream(file);                                FileOutputStream outputStream = new FileOutputStream(f);                                copyStream(inputStream, outputStream);                            }                        }                        Bitmap bitmap = ImageResizeUtils.resizeImage(f.getAbsolutePath(), 1080);                        int width = bitmap.getWidth();                        int height = bitmap.getHeight();                        FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());                        if (bitmap != null) {                            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos)) {                                fos.close();                                fos.flush();                            }                            if (!bitmap.isRecycled()) {                                bitmap.isRecycled();                            }                            System.out.println("f = " + f.length());                            postFile(f);                        }                    }                } catch (Exception e) {                    e.printStackTrace();                }                break;            case INTENTFORCAMERA:                try {                    File file = new File(Utils.photoCacheDir, LocalPhotoName);                    Bitmap bitmap = ImageResizeUtils.resizeImage(file.getAbsolutePath(), 1080);                    int width = bitmap.getWidth();                    int height = bitmap.getHeight();                    FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());                    if (bitmap != null) {                        if (bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos)) {                            fos.close();                            fos.flush();                        }                        if (!bitmap.isRecycled()) {                            bitmap.isRecycled();                        }                        System.out.println("f = " + file.length());                        postFile(file);                    }                } catch (Exception e) {                    e.printStackTrace();                }                break;        }    }    public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception {        try {            byte[] buffer = new byte[1024];            int len = 0;            while ((len = inputStream.read(buffer)) != -1) {                outStream.write(buffer, 0, len);            }            outStream.flush();        } catch (IOException e) {            e.printStackTrace();        }finally {            if(inputStream != null){                inputStream.close();            }            if(outStream != null){                outStream.close();            }        }    }    public void post(){        OkHttpClient client = new OkHttpClient();        RequestBody requestBody = new FormBody.Builder()                .add("username","1507D")                .add("password","1507D")                .add("postkey","1503")                .build();        Request request = new Request.Builder().url("http://qhb.2dyt.com/Bwei/login")                .post(requestBody).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 {                System.out.println("response = " + response.body().string());            }        });    }    public void cache(){        new Thread(new Runnable() {            @Override            public void run() {                try {                    int cacheSize = 10 * 1024 * 1024; // 10 MiB                    Cache cache = new Cache(getCacheDir(), cacheSize);                    OkHttpClient client = new OkHttpClient.Builder()                            .addInterceptor(new Interceptor())                            .cache(cache)                            .build();                    Request request = new Request.Builder()                            .cacheControl(CacheControl.FORCE_NETWORK)                            .url("http://publicobject.com/helloworld.txt")                            .build();                    String response1Body;                    Response response1 = client.newCall(request).execute();                    if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);                    response1Body = response1.body().string();                    System.out.println("Response 1 response:          " + response1);                    System.out.println("Response 1 cache response:    " + response1.cacheResponse());                    System.out.println("Response 1 network response:  " + response1.networkResponse());                    String response2Body;//// {//                    Response response2 = client.newCall(request).execute();////////                   Call call1 =   client.newCall(request);////////                    call1.cancel();////                    if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);////                    response2Body = response2.body().string();//                    System.out.println("Response 2 response:          " + response2);//                    System.out.println("Response 2 cache response:    " + response2.cacheResponse());//                    System.out.println("Response 2 network response:  " + response2.networkResponse());//////                    System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));//                }catch (Exception e) {                }            }        }).start();    }    public void percall(){        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();        OkHttpClient client1 = client.newBuilder().connectTimeout(10, TimeUnit.SECONDS).build();        OkHttpClient client2 = client.newBuilder().connectTimeout(100, TimeUnit.SECONDS).build();    }}
Utils类
package com.bwie.asus.okhttp;import android.os.Environment;import android.os.StatFs;import java.io.File;import java.io.IOException;/** * Created by ASUS on 2017/9/27. */public class Utils {    public static final String DLIAO = "dliao" ;    public static File photoCacheDir = Utils.createCacheDir(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + DLIAO);    public static String cacheFileName = "myphototemp.jpg";    public static boolean isSDCardExist() {        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            return true;        } else {            return false;        }    }    public static void delFolder(String folderPath) {        try {            delAllFile(folderPath);            String filePath = folderPath;            filePath = filePath.toString();            File myFilePath = new File(filePath);            myFilePath.delete();        } catch (Exception e) {            e.printStackTrace();        }    }    public static boolean delAllFile(String path) {        boolean flag = false;        File file = new File(path);        if (!file.exists()) {            return flag;        }        if (!file.isDirectory()) {            return flag;        }        String[] tempList = file.list();        File temp = null;        for (int i = 0; i < tempList.length; i++) {            if (path.endsWith(File.separator)) {                temp = new File(path + tempList[i]);            } else {                temp = new File(path + File.separator + tempList[i]);            }            if (temp.isFile()) {                temp.delete();            }            if (temp.isDirectory()) {                delAllFile(path + "/" + tempList[i]);                delFolder(path + "/" + tempList[i]);                flag = true;            }        }        return flag;    }    public static boolean deleteOldAllFile(final String path) {        try {            new Thread(new Runnable() {                @Override                public void run() {                    delAllFile(Environment.getExternalStorageDirectory() + File.separator + DLIAO);                }            }).start();        } catch (Exception e) {            e.printStackTrace();            return false;        }        return true;    }    public static File createCacheDir(String dirPath) {        File dir = new File(dirPath);;        if(isSDCardExist()){            if (!dir.exists()) {                dir.mkdirs();            }        }        return dir;    }    public static File createNewFile(File dir, String fileName) {        File f = new File(dir, fileName);        try {            if (!dir.exists()) {                dir.mkdirs();            }            f.createNewFile();        } catch (IOException e) {            e.printStackTrace();        }        return f;    }    public static File getCacheFile() {        return createNewFile(photoCacheDir, cacheFileName);    }    public static File getMyFaceFile(String fileName) {        return createNewFile(photoCacheDir, fileName);    }    public static int getAvailableExternalStorageSize() {        if (isSDCardExist()) {            File path = Environment.getExternalStorageDirectory();            StatFs stat = new StatFs(path.getPath());            long blockSize = stat.getBlockSize();            long availableBlocks = stat.getAvailableBlocks();            long memorySize = availableBlocks * blockSize;            if(memorySize < 10*1024*1024){                return 1;            }else{                return 2;            }        } else {            return 0;        }    }}
Interceptor类
package com.bwie.asus.okhttp;import java.io.IOException;import okhttp3.Request;import okhttp3.Response;/** * Created by ASUS on 2017/9/27. */public class Interceptor implements okhttp3.Interceptor{    @Override    public Response intercept(Chain chain) throws IOException {        Request request = chain.request();        long t1 = System.currentTimeMillis();        Response response = chain.proceed(request);        long t2 = System.currentTimeMillis();        System.out.println("t2 = " +( t2-t1));        return response;    }}
ImageResizeUtils类
package com.bwie.asus.okhttp;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.media.ExifInterface;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import static android.graphics.BitmapFactory.decodeFile;/** * Created by ASUS on 2017/9/27. */public class ImageResizeUtils {    public static Bitmap resizeImage(String path, int specifiedWidth) throws Exception {        Bitmap bitmap = null;        FileInputStream inStream = null;        File f = new File(path);        System.out.println(path);        if (!f.exists()) {            throw new FileNotFoundException();        }        try {            inStream = new FileInputStream(f);            int degree = readPictureDegree(path);            BitmapFactory.Options opt = new BitmapFactory.Options();            opt.inJustDecodeBounds = true;            decodeFile(path, opt);            int inSampleSize = 1;            final int width = opt.outWidth;//            1000 980            if (width > specifiedWidth) {                inSampleSize = (int) (width / (float) specifiedWidth);            }            opt.inSampleSize = inSampleSize;//            opt.inPurgeable = true;            bitmap = BitmapFactory.decodeStream(inStream, null, opt);            // bitmap = BitmapFactory.decodeFile(path, opt);            if (inStream != null) {                try {                    inStream.close();                } catch (IOException e) {                    e.printStackTrace();                } finally {                    inStream = null;                }            }            if (bitmap == null) {                return null;            }            Matrix m = new Matrix();            if (degree != 0) {                //               m.setRotate(degree);                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);            }            float scaleValue = (float) specifiedWidth / bitmap.getWidth();            m.setScale(scaleValue, scaleValue);            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);            return bitmap;        } catch (OutOfMemoryError e) {            e.printStackTrace();            return null;        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    public static int readPictureDegree(String path) {        int degree = 0;        try {            ExifInterface exifInterface = new ExifInterface(path);            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);            switch (orientation) {                case ExifInterface.ORIENTATION_ROTATE_90:                    degree = 90;                    break;                case ExifInterface.ORIENTATION_ROTATE_180:                    degree = 180;                    break;                case ExifInterface.ORIENTATION_ROTATE_270:                    degree = 270;                    break;            }        } catch (IOException e) {            e.printStackTrace();        }        return degree;    }    public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception {        try {            byte[] buffer = new byte[1024];            int len = 0;            while ((len = inputStream.read(buffer)) != -1) {                outStream.write(buffer, 0, len);            }            outStream.flush();        } catch (IOException e) {            e.printStackTrace();        }finally {            if(inputStream != null){                inputStream.close();            }            if(outStream != null){                outStream.close();            }        }    }}
权限
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
xml
<Button    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/photo"/><Button    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/camear"/>

原创粉丝点击