OkHttp 封装

来源:互联网 发布:中国电信it研发中心 编辑:程序博客网 时间:2024/05/21 15:05
private OkHttpClient mClient;

private volatile static OKhttpManager sManager;//防止多个线程同时访问.比synchronized轻

private volatile static OKhttpManager manager;



private static Handler mHandler;
private Reader reader;

///////////////////////////////////////使用构造方法,完成初始化////////////////////////
public OKhttpManager() {
mClient = new OkHttpClient();
mHandler = new Handler();
}
///////////////////////////////////////使用单例模式,通过获取的方式拿到对象/////////////
public static OKhttpManager getInstance(){
if (sManager == null) {
sManager=new OKhttpManager();
}
return sManager;
}

//////////////////////////////////////////////定义接口//////////////////////////////////////
interface Func1{
void onResponse(String result);
}
interface Func2{
void onResponse(byte[] result);
}

interface Func3{
void onResponse(JSONObject jsonObject);
}

interface Func4{
void onResponse(Bean bean);
}

//////////////////////////////////////////////////使编写代码运行在主线程////////////////////
//处理请求网络成功的方法,返回的结果是json字符串
private static void onSuccessJsonStringMethod (final String jsonValue, final Func1 callBack){
//这里我用的是mHandler.post(new Runnable()){}方法更新UI
mHandler.post(new Runnable() {//代码是在UI线程执行
@Override
public void run() {
if (callBack!=null){
try{
callBack.onResponse(jsonValue);
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}

/**
* 返回响应的结果是json对象
* @param jsonValue
* @param callBack
*/
private void onSuccessJsonObjectMethod(final String jsonValue, final Func3 callBack){
mHandler.post(new Runnable() {
@Override
public void run() {
if (callBack!=null){
try{
callBack.onResponse(new JSONObject(jsonValue));
}catch(JSONException e){
e.printStackTrace();
}
}
}
});
}



/**
* 请求返回的是byte[] 数组
* @param data
* @param callBack
*/
private void onSuccessByteMethod(final byte[] data,final Func2 callBack){
mHandler.post(new Runnable() {
@Override
public void run() {
if (callBack!=null){
callBack.onResponse(data);
}
}
});
}


/**
* 返回的Bean对象到Func4接口中
* @param string
* @param callBack
*/
private void onSuccessJsonToBean(final String string, final Func4 callBack) {
mHandler.post(new Runnable() {
@Override
public void run() {
Gson gson=new Gson();
Bean bean=gson.fromJson(string,Bean.class);
callBack.onResponse(bean);
}
});
}
///////////////////////////下面就是可以调用的方法了///////////////////////////////////////////////////
/**
* 请求指定的url返回的结果是json字符串
* @param url
* @param callBack
*/
public void asyncJsonStringByURL(String url,final Func1 callBack){
final Request request = new Request.Builder().url(url).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response!=null&&response.isSuccessful()){
onSuccessJsonStringMethod(response.body().string(),callBack);
}
}
});
}

/**
* 返回响应的结果是bean对象
* @param url
* @param callBack
*/
public void getBeanMethod(String url, final Func4 callBack){
final Request request = new Request.Builder().url(url).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("网络错误"+e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response!=null&&response.isSuccessful()){
ResponseBody body = response.body();
reader = body.charStream();
String res=null;
BufferedReader bf=new BufferedReader(reader);
StringBuffer sb=new StringBuffer();
while ((res=bf.readLine())!=null){
sb.append(res);
}

onSuccessJsonToBean(new String(sb.toString().getBytes(),"UTF-8"),callBack);
}
}
});
}



/**
* 请求返回的是json对象
*
* @param url
* @param callBack
*/
public void asyncJsonObjectByURL(String url, final Func3 callBack) {
final Request request = new Request.Builder().url(url).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
onSuccessJsonObjectMethod(response.body().string(), callBack);
}
}
});
}
/**
* 请求返回的是byte字节数组
*/
public void asyncGetByteByURL(String url, final Func2 callBack) {
final Request request = new Request.Builder().url(url).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
onSuccessByteMethod(response.body().bytes(), callBack);
}
}
});
}

/**
* 表单提交
* @param url
* @param params
* @param callBack
*/
public void sendComplexForm(String url, Map<String, String> params, final Func1 callBack) {
FormBody.Builder form_builder = new FormBody.Builder();//表单对象,包含以input开始的对象,以html表单为主
RequestBody bodys=new FormBody.Builder().build();
//键值非空
if (params != null && !params.isEmpty()) {
for(Map.Entry<String,String> entry : params.entrySet()){
form_builder.add(entry.getKey(),entry.getValue());
}
}
RequestBody request_body = form_builder.build();
Request request = new Request.Builder().url(url).post(request_body).build();//采用post方式提交
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response!=null&&response.isSuccessful()){
onSuccessJsonStringMethod(response.body().string(), callBack);
}
}
});
}
////////////////////////////////////////////////////////////
////post请求发送json字符串
////////////////////////////////////////////////////////////
public void sendJsonStr(String url, String jsonStr, final Func1 callBack){


MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonStr);
Request request = new Request.Builder().url(url).post(body).build();//采用post方式提交

mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
onSuccessJsonStringMethod(response.body().string(),callBack);
}
});
}
////////////////////////////////////////////////////////////
////post请求上传文件
////////////////////////////////////////////////////////////
public void upLoadFile(String url,File file,final Func1 callBack){
MediaType type = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(type, file);
MultipartBody body1=new MultipartBody.Builder().addFormDataPart("a",file.getName(),body).build();
Request request=new Request.Builder().url(url).post(body1).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("上传文件失败");
}

@Override
public void onResponse(Call call, Response response) throws IOException {
onSuccessJsonStringMethod(response.body().string(),callBack);
}
});
}
}