OKhttp的封装(上)

时间:2023-12-30 13:12:26
自从介绍了OKhttp3的一些基本使用之后,又偷了下懒,所以它的续篇被搁置了一段时间,现在补充。

OKhttpManager.Class  请求工具类
 package com.example.administrator.okhttp3;

 import android.os.Handler;
import android.os.Looper; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response; /**
* Created by ${火龙裸先生} on 2016/9/28.
* 邮箱:791335000@qq.com
* <p/>
* OKhttpManager OKhttp封装类
*/
public class OKhttpManager {
private OkHttpClient client;
private static OKhttpManager oKhttpManager;
private Handler mHandler; /**
* 单例获取 OKhttpManager实例
*/
private static OKhttpManager getInstance() {
if (oKhttpManager == null) {
oKhttpManager = new OKhttpManager();
}
return oKhttpManager;
} private OKhttpManager() {
client = new OkHttpClient();
mHandler = new Handler(Looper.getMainLooper());
} /**************
* 内部逻辑处理
****************/
private Response p_getSync(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
return response;
} private String p_getSyncAsString(String url) throws IOException {
return p_getSync(url).body().string();
} private void p_getAsync(String url, final DataCallBack callBack) {
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
deliverDataFailure(call, e, callBack);
} @Override
public void onResponse(Call call, Response response) {
try {
String result = response.body().string();
deliverDataSuccess(result, callBack);
} catch (IOException e) {
deliverDataFailure(call, e, callBack);
}
}
});
} private void p_postAsync(String url, Map<String, String> params, final DataCallBack callBack) {
RequestBody requestBody = null; if (params == null) {
params = new HashMap<String, String>();
}
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey().toString();
String value = null;
if (entry.getValue() == null) {
value = "";
} else {
value = entry.getValue().toString();
}
builder.add(key, value);
}
requestBody = builder.build();
final Request request = new Request.Builder().url(url).post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
deliverDataFailure(call, e, callBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
try {
String result = response.body().string();
deliverDataSuccess(result, callBack);
} catch (IOException e) {
deliverDataFailure(call, e, callBack);
}
}
});
} /**
* 数据分发的方法
*/
private void deliverDataFailure(final Call call, final IOException e, final DataCallBack callBack) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
callBack.requestFailure(call, e);
}
}
});
} private void deliverDataSuccess(final String result, final DataCallBack callBack) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
callBack.requestSuccess(result);
}
}
});
} /******************
* 对外公布的方法
*****************/
public static Response getSync(String url) throws IOException {
return getInstance().p_getSync(url);//同步GET,返回Response类型数据
} public static String getSyncAsString(String url) throws IOException {
return getInstance().p_getSyncAsString(url);//同步GET,返回String类型数据
} public static void getAsync(String url, DataCallBack callBack) {
getInstance().p_getAsync(url, callBack);//异步GET请求
} public static void postAsync(String url, Map<String, String> params, DataCallBack callBack) {
getInstance().p_postAsync(url, params, callBack);//异步POST请求
} /**
* 数据回调接口
*/
public interface DataCallBack {
void requestFailure(Call call, IOException e); void requestSuccess(String result);
} }

MainActivity.class   工具类的调用方法


 package com.example.administrator.okhttp3;

 import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static OkHttpClient client = new OkHttpClient();
private Request request;
private Response response; private Button button1, button2, button3, button4;
private TextView textView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.btn_one);
button2 = (Button) findViewById(R.id.btn_two);
button3 = (Button) findViewById(R.id.btn_three);
button4 = (Button) findViewById(R.id.btn_four);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
textView = (TextView) findViewById(R.id.tv);
} @Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_one://同步GET 调用方法 new Thread(new Runnable() {
@Override
public void run() {
try {
final String message = OKhttpManager.getSyncAsString("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9");
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(message);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start(); break;
case R.id.btn_two://异步GET 调用方法
OKhttpManager.getAsync("http://web.juhe.cn:8080/finance/exchange/rmbquot", new OKhttpManager.DataCallBack() {
@Override
public void requestFailure(Call call, IOException e) {
/**
* 加载失败,回调这个方法
* */
} @Override
public void requestSuccess(String result) {
textView.setText(result);
}
});
break;
case R.id.btn_three://POST提交表单 调用方法
Map<String, String> params = new HashMap<>();
params.put("cellphone", "123456");//用户名
params.put("password", "123456");//密码
OKhttpManager.postAsync("http://58.250.31.19:28080/afeducation/appfront/main/loginUser_app.do", params, new OKhttpManager.DataCallBack() {
@Override
public void requestFailure(Call call, IOException e) {
textView.setText(e.toString());
} @Override
public void requestSuccess(String result) {
textView.setText(result);
}
});
break;
case R.id.btn_four://文件下载 调用方法 break;
}
}
}

activity_main.xml   布局文件

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.okhttp3.MainActivity"> <Button
android:id="@+id/btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="同步get" /> <Button
android:id="@+id/btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="异步get" /> <Button
android:id="@+id/btn_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post提交表单" /> <Button
android:id="@+id/btn_four"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文件下载" /> <TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text" />
</LinearLayout>

以前都是用Volley去进行网络交互,时间久了,也想换换新的东西。网络请求框架各具特色,需要自己不断探索和选择。加油!