自己封装了一个Okhttp网络请求,操作简单,可区分一个类中的不同请求

本文介绍了一个基于OkHttp的网络请求封装实现,包括GET、POST请求及文件上传功能,并提供了回调接口以方便处理响应结果。

第一个类:发送请求类Mananger


package dss.com.diexunkj.net;

import android.nfc.Tag;
import android.os.Looper;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import android.os.Handler;

/**
 * Created by huguomin on 2017/2/23.
 */

public class DXHttpManager {

    private static final int TIME_OUT = 30;
    private static OkHttpClient mOkHttpClient = null;
    private static OkHttpClient.Builder okHttpClientBuilder;
    private Handler mDeliveryHandler;
    private Request build;

    //单例设计
    private static DXHttpManager mInstance;
    private DXHttpManager() {
        okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS); //链接超时时间
        okHttpClientBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);   //写入超时时间
        okHttpClientBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);    //读取超时时间
        okHttpClientBuilder.followRedirects(true);                      //设置重定向 其实默认也是true
        this.mDeliveryHandler = new Handler(Looper.getMainLooper());    //初始化handler
        mOkHttpClient = okHttpClientBuilder.build();                    //初始化okHttpClient
    }
    public static DXHttpManager getmInstance() {
        if (mInstance == null) {
            synchronized (DXHttpManager.class) {
                if (mInstance == null) {
                    mInstance = new DXHttpManager();
                }
            }
        }
        return mInstance;
    }
    /**
     * 发送get请求,带参数直接传入parma,不带参数直接传null
     */
    public void sendGetRequest(String url, RequestParams params, final int tag, final DXHttpListener listener) {
        StringBuilder urlBuilder = new StringBuilder(url).append("?");
        if (params != null) {
            for (Map.Entry<String, String> entry : params.urlParams.entrySet()) {
                // 将请求参数逐一添加到请求体中
                urlBuilder.append(entry.getKey()).append("=")
                        .append(entry.getValue())
                        .append("&");
            }
        }
        Request request = new Request.Builder()
                .url(urlBuilder.substring(0, urlBuilder.length() - 1)) //要把最后的&符号去掉
                .get()
                .build();
      mOkHttpClient.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
              deliveryFailure(call,e,listener,tag);
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
              deliverySuccessRequest(call,response,listener,tag);
          }
      });

    }

    /**
     * 发送post请求,带参数直接传入parma
     */
    public void sendPostRequest(String  url, RequestParams params, final int tag, final DXHttpListener listener){
        FormBody.Builder mFormBodybuilder = new FormBody.Builder();
        if(params!=null){
            for(Map.Entry<String,String> entry: params.urlParams.entrySet()){
                // 将请求参数逐一添加到请求体中
                mFormBodybuilder.add(entry.getKey(),entry.getValue());
            }
        }
        FormBody mFormBody=mFormBodybuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(mFormBody)
                .build();
         mOkHttpClient.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
                deliveryFailure(call,e,listener,tag);
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
                deliverySuccessRequest(call,response,listener,tag);
          }
      });
    }

    //请求成功,讲回调切换到主线程
    private  void deliverySuccessRequest(Call call, final Response response, final DXHttpListener listener, final int tag) {
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    listener.onSuccess(new RequestBean(tag,response));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //请求失败,讲回调切换到主线程
    private  void deliveryFailure(Call call, final IOException e, final DXHttpListener listener, final int tag) {
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onFailed(tag,e);
            }
        });
    }

    /**
     * 文件上传请求
     * @return
     */
    private static final MediaType FILE_TYPE = MediaType.parse("application/octet-stream");
    public void createMultiPostRequest(String url, RequestParams params, final DXHttpListener listener, final int tag) {
        MultipartBody.Builder requestBody = new MultipartBody.Builder();
        requestBody.setType(MultipartBody.FORM);
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.fileParams.entrySet()) {
                if (entry.getValue() instanceof File) {
                    requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
                            RequestBody.create(FILE_TYPE, (File) entry.getValue()));
                } else if (entry.getValue() instanceof String) {

                    requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
                            RequestBody.create(null, (String) entry.getValue()));
                }
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                deliveryFailure(call,e,listener,tag);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                deliverySuccessRequest(call,response,listener,tag);
            }
        });
    }

}


第二个类:其实就是一个map集合

package dss.com.diexunkj.net;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RequestParams {

    public ConcurrentHashMap<String, String> urlParams = new ConcurrentHashMap<String, String>();
    public ConcurrentHashMap<String, Object> fileParams = new ConcurrentHashMap<String, Object>();

    /**
     * Constructs a new empty {@code RequestParams} instance.
     */
    public RequestParams() {
        this((Map<String, String>) null);
    }

    /**
     * Constructs a new RequestParams instance containing the key/value string
     * params from the specified map.
     *
     * @param source the source key/value string map to add.
     */
    public RequestParams(Map<String, String> source) {
        if (source != null) {
            for (Map.Entry<String, String> entry : source.entrySet()) {
                put(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Constructs a new RequestParams instance and populate it with a single
     * initial key/value string param.
     *
     * @param key   the key name for the intial param.
     * @param value the value string for the initial param.
     */
    public RequestParams(final String key, final String value) {
        this(new HashMap<String, String>() {
            {
                put(key, value);
            }
        });
    }

    /**
     * Adds a key/value string pair to the request.
     *
     * @param key   the key name for the new param.
     * @param value the value string for the new param.
     */
    public void put(String key, String value) {
        if (key != null && value != null) {
            urlParams.put(key, value);
        }
    }

    public void put(String key, Object object) throws FileNotFoundException {

        if (key != null) {
            fileParams.put(key, object);
        }
    }

    public boolean hasParams() {
        if(urlParams.size() > 0 || fileParams.size() > 0){

            return true;
        }
        return false;
    }
}


第三个类:response的bean类

public class RequestBean {
    public  int tag;
    public Response response;
    public RequestBean(int tag,Response response){
        this.tag = tag;
        this.response = response;
    }
}


第四个类:回调的接口

public interface DXHttpListener {
    void onSuccess(RequestBean bean) throws IOException;
    void onFailed(int tag, IOException e);
}


使用

发送请求

 DXHttpManager.getmInstance().sendGetRequest(url,null,100,this);

回调方法

@Override
public void onSuccess(RequestBean bean) throws IOException {
    switch (bean.tag){
        case 100:
            showText.setText(bean.response.body().string()+"");
            break;
    }
}

@Override
public void onFailed(int tag, IOException e) {
    showText.setText(e.toString());
    Log.e("=======",e.toString());
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值