第一个类:发送请求类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()); }
本文介绍了一个基于OkHttp的网络请求封装实现,包括GET、POST请求及文件上传功能,并提供了回调接口以方便处理响应结果。
752

被折叠的 条评论
为什么被折叠?



