Okhttp使用随笔

一、okhttp的简单使用,主要包含:
1.一般的get请求
2.一般的post请求
3.基于http的文件上传
4.文件下载
5.加载图片
6.支持请求回调,直接返回对象、对象集合
7.支持session的保持
二、使用教程
(一)Http get

//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
                .url("https://github.com/hongyangAndroid")
                .build();
//new call
Call call = mOkHttpClient.newCall(request); 
//请求加入调度
call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
            }

            @Override
            public void onResponse(final Response response) throws IOException
            {
                    //String htmlStr =  response.body().string();
            }
        });       

1.以上就是发送一个get请求的步骤,首先构造一个Requet对象,参数最起码有一个url,也可通过reques.Builder设置更多的参数、比如header,method等。
2、然后通过request的对象去构造得到一个call对象,类似于将你的请求封装成了任务,既然是任务,就会有execute()和cancel()等方法、
3.最后我们希望以异步的方式去执行请求,调用的是call.execute(),将call加入到调度队列,然后等待任务完成,在callback中获取结果。
注意:
onResponse回调的参数是response,可以通过response.body().string()获取字符串;通过response.body().bytes()获取二进制字节数组;通过response.body().byteStream()获取inputStream。onResponse执行的线程并不是UI线程,如果操纵控件,需要handler、runOnUiThread、AsyncTask等执行。
(二)基于Http的文件上传
可以构造RequestBody的Builder,叫做MultiparBuilder。当我们需要做类似的表单上传时,就可以用它构造我们的requestBody。

File file = new File(Environment.getExternalStorageDirectory(), "balabala.mp4");

RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

RequestBody requestBody = new MultipartBuilder()
     .type(MultipartBuilder.FORM)
     .addPart(Headers.of(
          "Content-Disposition", 
              "form-data; name=\"username\""), 
          RequestBody.create(null, "user"))
     .addPart(Headers.of(
         "Content-Disposition", 
         "form-data; name=\"mFile\"; 
         filename=\"wjd.mp4\""), fileBody)
     .build();

Request request = new Request.Builder()
    .url("http://192.168.1.103:8080/okHttpServer/fileUpload")
    .post(requestBody)
    .build();

Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
    //...
});

上述代码向服务器传递了一个键值对username:user和一个文件。可以通过MultipartBuilder的addPart方法可以添加键值对或者文件。

okHttp简单封装

OkHttpClientManager

package com.xl.test;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;

/**
 * Created by hushendian on 2017/6/21.
 */

public class OkHttpClientManager {
    private static OkHttpClientManager mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;
    private Gson mGson;

    private static final String TAG = "OkHttpClientManager";

    private OkHttpClientManager() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy
                .ACCEPT_ORIGINAL_SERVER));
        mHandler = new Handler(Looper.getMainLooper());
        mGson = new Gson();

    }

    public static OkHttpClientManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpClientManager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpClientManager();
                }

            }
        }
        return mInstance;
    }

    private Request _getRequest(String url) throws IOException {
        return new Request.Builder().url(url).build();
    }

    /**
     * 同步的get请求
     *
     * @param url
     * @return Response
     * @throws IOException
     */
    private Response _getAsyn(String url) throws IOException {
        final Request request = _getRequest(url);
        Call call = mOkHttpClient.newCall(request);
        Response response = call.execute();
        return response;
    }

    /**
     * 同步的get请求
     *
     * @param url
     * @return String
     * @throws IOException
     */
    private String _getAsString(String url) throws IOException {

        Response response = _getAsyn(url);

        return response.body().string();
    }

    /**
     * 异步get请求
     *
     * @param url
     * @param callback
     */
    private void _getAsyn(String url, final ResultCallback callback) throws IOException {
        final Request request = _getRequest(url);
        deliveryResult(request, callback);
    }

    /**
     * 同步post
     *
     * @param url
     * @param params
     * @return
     */
    private Response _post(String url, Param... params) throws IOException {
        Request request = buildRequsest(url, params);
        Response response = mOkHttpClient.newCall(request).execute();
        return response;

    }

    /**
     * 同步post
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    private String _postAsynString(String url, Param... params) throws IOException {
        Response response = _post(url, params);
        return response.body().string();
    }

    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     * @param params
     */
    private void _postAsy(String url, ResultCallback callback, Param... params) {
        Request request = buildRequsest(url, params);
        deliveryResult(request, callback);
    }

    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     * @param params
     */
    private void _postAsyn(String url, ResultCallback callback, Map<String, String> params) {
        Param[] param = map2Params(params);
        Request request = buildRequsest(url, param);
        deliveryResult(request, callback);
    }

    /**
     * 异步文件上传post
     *
     * @param url
     * @param files
     * @param filekeys
     * @param params
     * @return
     * @throws IOException
     */
    private Response _post(String url, File[] files, String[] filekeys, Param... params) throws
            IOException {

        Request request = buildMultipartFormRequest(url, files, filekeys, params);

        return mOkHttpClient.newCall(request).execute();
    }

    private Response _post(String url, File files, String filekeys) throws
            IOException {

        Request request = buildMultipartFormRequest(url, new File[]{files}, new
                String[]{filekeys}, null);

        return mOkHttpClient.newCall(request).execute();
    }

    private Response _post(String url, File files, String filekeys, Param... params) throws
            IOException {

        Request request = buildMultipartFormRequest(url, new File[]{files}, new
                String[]{filekeys}, params);

        return mOkHttpClient.newCall(request).execute();
    }

    /**
     * 异步基于post文件上传
     *
     * @param url
     * @param callback
     * @param files
     * @param filekeys
     * @param params
     */
    private void _postAsyn(String url, ResultCallback callback, File[] files, String[] filekeys,
                           Param... params) {
        Request request = buildMultipartFormRequest(url, files, filekeys, params);
        deliveryResult(request, callback);
    }

    /**
     * 异步基于post文件上传,单文件且携带其他form参数上传
     *
     * @param url
     * @param callback
     * @param files
     * @param filekeys
     * @param params
     */
    private void _postAsyn(String url, ResultCallback callback, File files, String filekeys,
                           Param... params) {
        Request request = buildMultipartFormRequest(url, new File[]{files}, new
                String[]{filekeys}, params);
        deliveryResult(request, callback);
    }

    /**
     * 异步基于post文件上传,单文件不携带其他form参数上传
     *
     * @param url
     * @param callback
     * @param files
     * @param filekeys
     */
    private void _postAsyn(String url, ResultCallback callback, File files, String filekeys
    ) {
        Request request = buildMultipartFormRequest(url, new File[]{files}, new
                String[]{filekeys}, null);
        deliveryResult(request, callback);
    }

    /**
     * 异步下载
     *
     * @param url
     * @param destFileDir
     * @param callback
     * @throws IOException
     */
    private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback
            callback) throws
            IOException {
        Request request = _getRequest(url);
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                sendFailedStringCallback(request, e, callback);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                savetodestFileDir(response, destFileDir, url, callback);
            }
        });
    }


    private void _displayImage(final String url, final ImageView imageView, final int errorId)
            throws
            IOException {
        Request request = _getRequest(url);
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                setErrorResId(imageView, errorId);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                setSuccessImage(imageView, response, url, errorId);
            }
        });

    }

    /**
     * 显示成功后的图片
     *
     * @param imageView
     * @param response
     * @throws IOException
     */
    private void setSuccessImage(final ImageView imageView, Response response, String url, int
            errorId) throws
            IOException {
        InputStream is = null;
        try {
            is = response.body().byteStream();
            ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);
            ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(imageView);
            int insampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);
            try {
                is.reset();
            } catch (IOException e) {
                response = _getAsyn(url);
                is = response.body().byteStream();
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inSampleSize = insampleSize;
            final Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });

        } catch (Exception e) {
            setErrorResId(imageView, errorId);
        } finally {
            if (is != null) {
                is.close();
            }
        }

    }


    private void setErrorResId(final ImageView imageView, final int errorId) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                imageView.setImageResource(errorId);
            }
        });
    }

    /**
     * 保存下载的文件到指定目录
     *
     * @param response
     * @param destFileDir
     * @param url
     * @param callback
     */
    private void savetodestFileDir(Response response, String destFileDir, String url,
                                   ResultCallback callback) {
        InputStream is = null;
        byte[] bytes = new byte[2048];
        int len = 0;
        FileOutputStream os = null;
        try {
            is = response.body().byteStream();
            File file = new File(destFileDir, getFileName(url));
            os = new FileOutputStream(file);
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
            sendSendSuccessStringCallback(file.getAbsolutePath(), callback);
        } catch (IOException e) {
            sendFailedStringCallback(response.request(), e, callback);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }

            } catch (IOException e) {

            }


        }


    }

    private String getFileName(String url) {
        int pos = url.lastIndexOf("/");
        return (pos < 0) ? url : url.substring(pos + 1, url.length());
    }

    /**
     * 异步上传文件获取request
     *
     * @param url
     * @param files
     * @param filekeys
     * @param params
     * @return
     */
    private Request buildMultipartFormRequest(String url, File[] files, String[] filekeys,
                                              Param[] params) {
        params = validateParam(params);
        MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
        for (Param param : params) {
            builder.addPart(Headers.of("Content-Disposition", "form-data;name=\"" + param.key +
                    "\""), RequestBody.create(null, param.value));
        }
        if (files != null) {
            RequestBody fBody = null;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String fileName = file.getName();
                fBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
                builder.addPart(Headers.of("Content-Disposition", "form-data,name=\"" + files[i]
                        + "\""), fBody);
            }
        }
        RequestBody body = builder.build();
        return new Request.Builder().url(url).post(body).build();
    }

    /**
     * 获取文件后缀的方法
     *
     * @param path
     * @return
     */
    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentType = fileNameMap.getContentTypeFor(path);
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return contentType;
    }

    private Param[] validateParam(Param[] params) {
        if (params == null)
            return new Param[0];
        else return params;
    }

    /**
     * 返回post情况下的Request
     *
     * @param url
     * @param params
     * @return
     */
    private Request buildRequsest(String url, Param... params) {
        if (params == null) {
            params = new Param[0];
        }
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Param param : params) {
            builder.add(param.key, param.value);
        }
        RequestBody body = builder.build();

        return new Request.Builder().url(url).post(body).build();
    }

    /**
     * 请求接口结果回调
     *
     * @param request
     * @param callback
     */
    private void deliveryResult(Request request, final ResultCallback callback) {
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                sendFailedStringCallback(request, e, callback);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String result = response.body().string();
                    if (callback.mType == String.class) {
                        sendSendSuccessStringCallback(response, callback);
                    } else {
                        Object o = mGson.fromJson(result, callback.mType);
                        sendSendSuccessStringCallback(o, callback);
                    }


                } catch (IOException e) {
                    sendFailedStringCallback(response.request(), e, callback);
                }

            }
        });
    }


    /**
     * 请求失败回调
     *
     * @param request
     * @param e
     * @param callback
     */
    private void sendFailedStringCallback(final Request request, final IOException e, final
    ResultCallback callback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onError(request, e);
                }
            }
        });

    }

    /**
     * 请求成功结果回调
     *
     * @param response
     * @param callback
     */
    private void sendSendSuccessStringCallback(final Object response, final ResultCallback
            callback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onResponse(response);
            }
        });
    }

    /**
     * MAP转化为Param类型
     *
     * @param map
     * @return
     */
    private Param[] map2Params(Map<String, String> map) {
        if (map == null) {
            return new Param[0];
        }
        int size = map.size();
        Param[] params = new Param[size];
        int i = 0;
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            params[i++] = new Param(entry.getKey(), entry.getValue());
        }

        return params;
    }

    /**
     * 自定义接口
     *
     * @param <T>
     */
    public static abstract class ResultCallback<T> {
        Type mType;

        public ResultCallback() {
            mType = getSuperclassTypeParameter(getClass());
            Log.d(TAG, "ResultCallback: " + mType);
        }

        static Type getSuperclassTypeParameter(Class<?> subclass) {
            Type supperclass = subclass.getGenericSuperclass();
            if (supperclass instanceof Class) {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterizedType = (ParameterizedType) supperclass;
            return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
        }

        public abstract void onError(Request request, Exception e);

        public abstract void onResponse(T response);
    }

    public static class Param {
        public Param() {

        }

        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }

        String key;
        String value;
    }

    //===================================对外公布的方法=======================
    public static Response getAsyn(String url) throws IOException {
        return getInstance()._getAsyn(url);
    }

    public static String getAsString(String url) throws IOException {
        return getInstance()._getAsString(url);
    }

    public static void getAsyn(String url, ResultCallback callback) throws IOException {
        getInstance()._getAsyn(url, callback);
    }

    public static Response post(String url, Param... params) throws IOException {
        return getInstance()._post(url, params);
    }

    public static String postAsyn(String url, Param... params) throws IOException {
        return getInstance()._postAsynString(url, params);
    }

    public static void postAsyn(String url, ResultCallback callback, Param... params) throws
            IOException {
        getInstance()._postAsy(url, callback, params);
    }

    public static void postAsy(String url, ResultCallback callback, Map<String, String> params)
            throws IOException {
        getInstance()._postAsyn(url, callback, params);
    }

    public static Response post(String url, File[] files, String[] fileName, Param... params)
            throws IOException {
        return getInstance()._post(url, files, fileName, params);
    }

    public static Response post(String url, File file, String fileName)
            throws IOException {
        return getInstance()._post(url, file, fileName);
    }

    public static Response post(String url, File file, String fileName, Param... params)
            throws IOException {
        return getInstance()._post(url, file, fileName, params);
    }

    public static void postAsyn(String url, ResultCallback callback, File[] files, String[]
            fileName, Param... params)
            throws IOException {
        getInstance()._postAsyn(url, callback, files, fileName, params);
    }

    public static void postAsyn(String url, ResultCallback callback, File file, String fileName)
            throws IOException {
        getInstance()._postAsyn(url, callback, file, fileName);
    }

    public static void postAsyn(String url, ResultCallback callback, File file, String fileName,
                                Param... params)
            throws IOException {
        getInstance()._postAsyn(url, callback, file, fileName, params);
    }

    public static void displayImag(String url, ImageView imageView, int errorResId) throws
            IOException {
        getInstance()._displayImage(url, imageView, errorResId);
    }

    public static void displayImag(String url, ImageView imageView) throws
            IOException {
        getInstance()._displayImage(url, imageView, -1);
    }

    public static void downloadAsyn(String url, String disFileName, ResultCallback callback)
            throws IOException {
        getInstance()._downloadAsyn(url, disFileName, callback);
    }
}

ImageUtils

“`
public class ImageUtils
{
/**
* 根据InputStream获取图片实际的宽度和高度
*
* @param imageStream
* @return
*/
public static ImageSize getImageSize(InputStream imageStream)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(imageStream, null, options);
return new ImageSize(options.outWidth, options.outHeight);
}

public static class ImageSize
{
    int width;
    int height;

    public ImageSize()
    {
    }

    public ImageSize(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    @Override
    public String toString()
    {
        return "ImageSize{" +
                "width=" + width +
                ", height=" + height +
                '}';
    }
}

public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize)
{
    // 源图片的宽度
    int width = srcSize.width;
    int height = srcSize.height;
    int inSampleSize = 1;

    int reqWidth = targetSize.width;
    int reqHeight = targetSize.height;

    if (width > reqWidth && height > reqHeight)
    {
        // 计算出实际宽度和目标宽度的比率
        int widthRatio = Math.round((float) width / (float) reqWidth);
        int heightRatio = Math.round((float) height / (float) reqHeight);
        inSampleSize = Math.max(widthRatio, heightRatio);
    }
    return inSampleSize;
}

/**
 * 根据ImageView获适当的压缩的宽和高
 *
 * @param view
 * @return
 */
public static ImageSize getImageViewSize(View view)
{

    ImageSize imageSize = new ImageSize();

    imageSize.width = getExpectWidth(view);
    imageSize.height = getExpectHeight(view);

    return imageSize;
}

/**
 * 根据view获得期望的高度
 *
 * @param view
 * @return
 */
private static int getExpectHeight(View view)
{

    int height = 0;
    if (view == null) return 0;

    final ViewGroup.LayoutParams params = view.getLayoutParams();
    //如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
    if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT)
    {
        height = view.getWidth(); // 获得实际的宽度
    }
    if (height <= 0 && params != null)
    {
        height = params.height; // 获得布局文件中的声明的宽度
    }

    if (height <= 0)
    {
        height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度
    }

    //如果宽度还是没有获取到,憋大招,使用屏幕的宽度
    if (height <= 0)
    {
        DisplayMetrics displayMetrics = view.getContext().getResources()
                .getDisplayMetrics();
        height = displayMetrics.heightPixels;
    }

    return height;
}

/**
 * 根据view获得期望的宽度
 *
 * @param view
 * @return
 */
private static int getExpectWidth(View view)
{
    int width = 0;
    if (view == null) return 0;

    final ViewGroup.LayoutParams params = view.getLayoutParams();
    //如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
    if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT)
    {
        width = view.getWidth(); // 获得实际的宽度
    }
    if (width <= 0 && params != null)
    {
        width = params.width; // 获得布局文件中的声明的宽度
    }

    if (width <= 0)

    {
        width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度
    }
    //如果宽度还是没有获取到,憋大招,使用屏幕的宽度
    if (width <= 0)

    {
        DisplayMetrics displayMetrics = view.getContext().getResources()
                .getDisplayMetrics();
        width = displayMetrics.widthPixels;
    }

    return width;
}

/**
 * 通过反射获取imageview的某个属性值
 *
 * @param object
 * @param fieldName
 * @return
 */
private static int getImageViewFieldValue(Object object, String fieldName)
{
    int value = 0;
    try
    {
        Field field = ImageView.class.getDeclaredField(fieldName);
        field.setAccessible(true);
        int fieldValue = field.getInt(object);
        if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
        {
            value = fieldValue;
        }
    } catch (Exception e)
    {
    }
    return value;

}

}
3565791/article/details/47911083

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值