Okhttp 简单理解

 


okhttp 调用自己封装的工具类

OKManager manager==OKManager.getInstance();

manager.asyncJsonStringbyURL(get_url, new OKManager.Func1() {
    @Override
    public void onResponse(String result) {
        Log.d("MainActivity", "==="+result);
    }
});


okhttp 封装的工具类


package com.mirrorlacation.okhttp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/1/12.
 * 封装工具类
 */
public class OKManager {

    private OkHttpClient client;
    private volatile static OKManager manager;
    private Handler handler;
    //提交json数据
    private static  final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    //提交字符串
    private static  final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown;charset=utf-8");

    private OKManager(){
        client=new OkHttpClient();
        handler=new Handler(Looper.getMainLooper());
    }
    //单例模式
    public  static OKManager getInstance(){
        OKManager instance=null;
        if(null==manager){
            synchronized (OKManager.class){
                if(null==instance){
                    instance=new OKManager();
                    manager=instance;
                }
            }
        }
        return  instance;
    }

    /**
     * 同步get请求,在Android开发中不常用,会阻塞UI线程
     * @param url
     * @return
     */
    public String syncGetbyURL(String url){
        //构建一个request请求
        Request request=new Request.Builder().url(url).build();
        Response response=null;
        try {
            response=client.newCall(request).execute();//同步请求数据
            if(response.isSuccessful()){
                return response.body().toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }
    /**
     * 异步get请求指定Url返回的结果是json字符串
     * @param url
     * @return
     */
    public void asyncJsonStringbyURL(String url, final Func1 callback){
        //构建一个request请求
        Request request=new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(null!=response&&response.isSuccessful()){
                    onSuccessJsonStringMethod(response.body().toString(),callback);
                }
            }
        });
    }
    /**
     * 异步get请求指定Url返回的结果是imageView类型 bitmap类型
     * @param url
     * @return
     */
    public void asyncDownLoadImagebyURL(String url, final Func3 callback){
        //构建一个request请求
        Request request=new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(null!=response&&response.isSuccessful()){
                   byte[] bytes=response.body().bytes();
                    Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                    callback.onResponse(bitmap);
                }
            }
        });
    }
    /**
     * 异步get请求指定Url返回的结果是byte字节数组
     * @param url
     * @return
     */
    public void asyncGetBytebyURL(String url, final Func2 callback){
        //构建一个request请求
        Request request=new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(null!=response&&response.isSuccessful()){
                    onSuccessbyteMethod(response.body().bytes(),callback);
                }
            }
        });
    }
    /**
     * 异步get请求指定Url返回的结果是json对象
     * @param url
     * @return
     */
    public void asyncJsonObjectbyURL(String url, final Func4 callback){
        //构建一个request请求
        Request request=new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(null!=response&&response.isSuccessful()){
                    onSuccessJsonObjectMethod(response.body().toString(),callback);
                }
            }
        });
    }
    //异步post 向服务器提交String请求
    public  void sendStringByPostMethod(String url,String content,final  Func4 callback){
        Request request=new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN,content)).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(null!=response&&response.isSuccessful()){
                    onSuccessJsonObjectMethod(response.body().toString(),callback);
                }
            }
        });
    }
    /**
     * 异步post 模拟表单提交
     * @param url
     * @param params
     * @param callback
     */
    public  void sendComplexForm(String url, Map<String,String> params, final Func4 callback){
        FormBody.Builder form_builder=new FormBody.Builder();//表单对象,包含以input开始的对象,以html表单为主
        if(null!=params&&!params.isEmpty()){
            for (Map.Entry<String,String> entry : params.entrySet()){
                form_builder.add(entry.getKey(),entry.getValue());
            }
        }
        RequestBody requestBody=form_builder.build();
        Request request=new Request.Builder().url(url).post(requestBody).build();//post提交
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(null!=response&&response.isSuccessful()){
                    onSuccessJsonObjectMethod(response.body().toString(),callback);
                }
            }
        });
    }
    /**
     * 返回结果为json字符串
     * @param jsonValues
     * @param callback
     */
    private void onSuccessJsonStringMethod(final String jsonValues,final Func1 callback){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(null!=callback){
                    try {
                        callback.onResponse(jsonValues);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    /**
     * 返回结果为 byte[]数组
     * @param data
     * @param callback
     */
    private void onSuccessbyteMethod(final byte[] data,final Func2 callback){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(null!=callback){
                    callback.onResponse(data);
                }
            }
        });
    }
    /**
     * 返回结果为json对象
     * @param jsonValues
     * @param callback
     */
    private void onSuccessJsonObjectMethod(final String jsonValues,final Func4 callback){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(null!=callback){
                    try {
                        callback.onResponse(new JSONObject(jsonValues));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    interface Func1{
        void onResponse(String result);
    }
    interface Func2{
        void onResponse(byte[] result);
    }
    interface Func3{
        void onResponse(Bitmap bitmap);
    }
    interface Func4{
        void onResponse(JSONObject jsonObject);
    }
}
转载别人的http://blog.csdn.net/lmj623565791/article/details/47911083 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值