Android OKHTTP3.4版本封装

OKHTTP是Android目前比较火的请求数据的框架,介绍可以看看官方的http://square.github.io/okhttp/


使用OKHTTP记得关联okio-1.11.0.jar包

OKHTTP得到的数据格式本身就是UTF-8的,如果需要,可以在返回的Response.body进行转换

OKHTTP建议全局只有一个OkHttpClient,如果需要更改初始化参数,可以使用newBuilder来colne新的对象进行初始化设置


OKHTTP有同步和异步的请求方法,这边使用异步请求的方式进行封装


OKHTTP的回调中不能更新UI,因此要自己再封装一层

这里封装有点不满意,如果有更好的,请告诉我一下

package com.example.textdemo;

import java.io.IOException;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class CallbackUTF8 implements Callback{
	Handler mHandler;
	
	public CallbackUTF8(Handler mHandler){
		super();
		this.mHandler = mHandler;
	}

	@Override
	public void onFailure(Call arg0, IOException arg1) {
		onFailure(arg1);
	}

	@Override
	public void onResponse(Call arg0, final Response arg1) throws IOException {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				try {
					onTResponse(arg1, arg1.body().string());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
	public abstract void onTResponse(Response response, String utf8);
	
	public abstract void onFailure(IOException arg1);
	
}





下面是对get,还有post的封装

package com.example.textdemo;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import android.text.TextUtils;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Request.Builder;
import okio.BufferedSink;


/**
 * 
 * @author Administrator
 *
 *
 * 如果要取得返回数据的header,可以在header.headers(),默认返回的字符串就是UTF-8-response.body().string(),get
 * 添加权限
 	
    //下面这些事使用到缓存的时候需要用的
    
    
    
 *
 */
public class OkHttpUtil {
	private static final String CHARSET_NAME = "UTF-8";
	//懒汉式
	private static OkHttpClient mOkHttpClient;
	//缓存路径
	private static final String FilePath = "OKHTTPCacheFile";
	//缓存大小
	private static final int cacheSize = 10 * 1024 * 1024; // 10 MiB
	//链接缓存时间	单位秒
	private static final int conectTimeout = 10;
	//写入缓存时间	单位秒
	private static final int writeTimeout = 10;
	//读取缓存时间	单位秒
	private static final int readTimeout = 30;
	
	
	private OkHttpUtil(){}
	//初始化
	public static void initOkHttpUtil(){
		if (mOkHttpClient == null){
			synchronized (OkHttpUtil.class) {
				if (mOkHttpClient == null){
					File cacheDirectory = new File(FilePath);
				    Cache cache = new Cache(cacheDirectory, cacheSize);
				    mOkHttpClient = new OkHttpClient().newBuilder()
				    		.cache(cache)		//最好不要更改cache目录
				            .connectTimeout(conectTimeout, TimeUnit.SECONDS)//设置相应时间
				            .writeTimeout(writeTimeout, TimeUnit.SECONDS)
				            .readTimeout(readTimeout, TimeUnit.SECONDS)
				    		.build();
				}
			}
		}
	}
	
	
	
	//TODO 克隆一个client,更改链接时间等参数设置
	public static OkHttpClient OkHttpClientClone(int conTime, int WriteTime, int ReadTime){
		if (mOkHttpClient == null){
			initOkHttpUtil();
		}
		OkHttpClient build = mOkHttpClient.newBuilder()
								.connectTimeout(conTime, TimeUnit.SECONDS)
								.writeTimeout(WriteTime, TimeUnit.SECONDS)
								.readTimeout(ReadTime, TimeUnit.SECONDS)
								.build();
		
		return build;
	}
	
	
	
	
	
	
	/**
	 * 异步请求数据,有回调参数
	 * @param url
	 * @param callback
	 */
	public static void get(String url, CallbackUTF8 callback){
		Request request = new Request.Builder()
                .url(url)
                .build();
		if (mOkHttpClient == null){
			initOkHttpUtil();
		}
		Call newCall = mOkHttpClient.newCall(request);
		newCall.enqueue(callback);
	}
	
	/**
	 * url参数较多时,可以使用map来拼接参数
	 * @param url
	 * @param headerMap
	 * @param callback
	 */
	public static void get(String url, Map params, CallbackUTF8 callback){
		String urls = buildParams(url, params);
		get(urls, callback);
	}
	
	
	/**
	 * 带header的get请求 如果url参数比较多,可以传递map,直观点
	 * @param urls
	 * @param params
	 * @param headerMap
	 * @param callback
	 */
	public static void get(String urls, Map params, Map headerMap, CallbackUTF8 callback){
		String url = buildParams(urls, params);
		Builder builder = new Request.Builder();
		for (String str : headerMap.keySet()) {
			builder.addHeader(str, headerMap.get(str));
		}
		Request request = builder
                .url(url)
                .build();
		if (mOkHttpClient == null){
			initOkHttpUtil();
		}
		Call newCall = mOkHttpClient.newCall(request);
		newCall.enqueue(callback);
	}
	
	
	
	
	
	/**
	 * 简单的post请求
	 * @param url
	 * @param params
	 * @param callback
	 */
	public static void post(String url, Map params, CallbackUTF8 callback){
		okhttp3.FormBody.Builder builder = new FormBody.Builder();
		for (String key : params.keySet()) {
			builder.add(key, params.get(key));
		}
		RequestBody body = builder.build();
		Request requeset = new Request.Builder()
							.url(url)
							.post(body)
							.build();
		if (mOkHttpClient == null){
			initOkHttpUtil();
		}
		Call newCall = mOkHttpClient.newCall(requeset);
		newCall.enqueue(callback);
		
	}
	
	
	/**
	 * 提交文件
	 * @param url
	 * @param file
	 * @param callback
	 */
	public void postFile(String url, File file, CallbackUTF8 callback){
		final MediaType MEDIA_TYPE_MARKDOWN
		  = MediaType.parse("text/x-markdown; charset=utf-8");
	    Request request = new Request.Builder()
	        .url(url)
	        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
	        .build();
		if (mOkHttpClient == null){
			initOkHttpUtil();
		}
		Call newCall = mOkHttpClient.newCall(request);
		newCall.enqueue(callback);
	}
	
	
	/**
	 * 拼接url参数
	 * @param url
	 * @param params
	 * @return
	 */
	public static String buildParams(String url, Map params) {
		if (TextUtils.isEmpty(url)) {
			return url;
		}
		if (params == null || params.size() == 0) {
			return url;
		}
		url += "?";
		Set keySet = params.keySet();
		Iterator itr = keySet.iterator();
		while (itr.hasNext()) {
			String key = itr.next();
			url += key + "=" + params.get(key) + "&";
		}
		url = url.substring(0, url.length() - 1);
		return url;
	}
	
	
	
	
	public static void cancelAllCall(){
		if (mOkHttpClient == null){
			return;
		}
		
		
	}
	
	
	
	
	
	
}












你可能感兴趣的:(Android OKHTTP3.4版本封装)