添加依赖:
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.google.code.gson:gson:2.2.4'
添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
声明Application:
<application
android:name=".MyApplication"
android:allowBackup="true"
CallBack:
public interface CallBack<T> {
//请求成功,数据正确,根据Bean返回我们的数据
void onSuccess(T response);
//请求成功后,数据回调失败,返回异常对象和异常信息
void onError(Throwable e);
//当错误信息返回在非200情况下(返回错误码和错误信息)
void onDefMessage(String code, String msg);
//网络404的情况(并不是没有网络)
void onNotFound();
//无网络的情况
void onNoNet();
}
CookiesManager:
public class CookiesManager implements CookieJar {
private final PersistentCookieStore cookieStore = new PersistentCookieStore(MyApplication.getContext());
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies != null && cookies.size() > 0) {
for (Cookie item : cookies) {
cookieStore.add(url, item);
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url);
return cookies;
}
}
MainActivity(调用,这个不用复制。。。):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Map<String , String> map = new HashMap<>();
MyApplication.getContext();
NetTool.getInstance().getRequest(this, "http://www.391k.com/api/xapi.ashx/info.json?key=bd_hyrzjjfb4modhj&size=10&page=1",
map, Bean.class, new CallBack<Bean>() {
@Override
public void onSuccess(Bean response) {
Toast.makeText(MainActivity.this, response.getData().getId() + "------", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onDefMessage(String code, String msg) {
}
@Override
public void onNotFound() {
}
@Override
public void onNoNet() {
}
});
}
}
MyApplication:
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
}
NetInterface:
public interface NetInterface {
//Post请求
<T> void postRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack);
//Get请求
<T> void getRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack);
//Put请求
<T> void putRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack);
//Delete请求
<T> void deleteRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack);
//Get直接返回Json数据
void jsonRequest(Context context, String url, Map<String, String> map, CallBack<String> callBack);
}
NetTool:
public class NetTool implements NetInterface {
private static NetTool sNetTool;
private NetInterface mInterface;
//双重校验锁(单例)
public static NetTool getInstance(){
if (sNetTool == null){
synchronized (NetTool.class){
if (sNetTool == null){
sNetTool = new NetTool();
}
}
}
return sNetTool;
}
private NetTool(){
mInterface = new OKTool();
}
@Override
public <T> void postRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
mInterface.postRequest(context,url,map,tClass,callBack);
}
@Override
public <T> void getRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
mInterface.getRequest(context,url,map,tClass,callBack);
}
@Override
public <T> void putRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
mInterface.putRequest(context,url,map,tClass,callBack);
}
@Override
public <T> void deleteRequest(Context context, String url, Map<String, String> map, Class<T> tClass, CallBack<T> callBack) {
mInterface.deleteRequest(context,url,map,tClass,callBack);
}
@Override
public void jsonRequest(Context context, String url, Map<String, String> map, CallBack<String> callBack) {
mInterface.jsonRequest(context,url,map,callBack);
}
}
OkTool:
public class OKTool implements NetInterface {
private OkHttpClient mOKHttpClient;
private Handler mHandler = new Handler(Looper.getMainLooper());
private Gson mGson;
//数据传输格式
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");//Json
public static final MediaType TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");//文本
private static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");//图片
public OKTool(){
//初始化
mGson = new Gson();
//进行超时时间及缓存大小配置
mOKHttpClient = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.cookieJar(new CookiesManager())
.connectTimeout(5, TimeUnit.SECONDS)
.cache(new Cache(Environment.getExternalStorageDirectory(), 10 * 1024 * 1024))
.build();
}
//Get请求
@Override
public <T> void getRequest(Context context, String url, Map<String, String> map, final Class<T> tClass, final CallBack<T> callBack) {
//20170821071534bfrz6G227lXl7Clk
final Request request = new Request.Builder().url(url)
.get()
.build();
mOKHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onError(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
// //获取 SessionID
// Headers headers = response.headers();
// List<String> cookies = headers.values("Set-Cookie");
// String session = cookies.get(0);
// String s = session.substring(session.indexOf("=")+1,session.indexOf(";"));
//
// Log.d("OKToolGet", "s:"+s);
//
//
Log.d("OKToolGet", str);
final T result;
//成功
if (response.code() == 200) {
try {
result = mGson.fromJson(str, tClass);
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(result);
}
});
} catch (final Throwable e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onError(e);
}
});
}
//网址404的情况
}else if (response.code() == 404){
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onNotFound();
}
});
}
//返回错误信息的情况
else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(str);
final String msg = jsonObject.getString("msg");
final String errorCode = jsonObject.getString("error_code");
Log.d("NewOkTool", msg);
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDefMessage(errorCode,msg);
// if (("2002").equals(errorCode)||("2001").equals(errorCode)){
// Utils.ShowTokenNewLogin(context);
// }else {
// callBack.onDefMessage(errorCode,msg);
// }
}
});
} catch (final JSONException e) {
e.printStackTrace();
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onError(e);
}
});
}
}
}
});
}
//Post请求
@Override
public <T> void postRequest(final Context context, String url, Map<String, String> map, final Class<T> tClass, final CallBack<T> callBack) {
//发送Json数据
final String jsonStr = mGson.toJson(map);
RequestBody requestBody = RequestBody.create(JSON,jsonStr);
final Request request = new Request.Builder().url(url)
.post(requestBody)
.build();
mOKHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onError(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
Log.d("OKToolPostStr", str);
final T result;
//成功
if (response.code() == 200) {
try {
result = mGson.fromJson(str, tClass);
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(result);
}
});
} catch (final Throwable e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onError(e);
}
});
}
//网址404的情况
}else if (response.code() == 404){
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onNotFound();
}
});
}
//返回错误信息的情况
else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(str);
//msg和error_code根据具体的接口返回变动
final String msg = jsonObject.getString("msg");
final String errorCode = jsonObject.getString("error_code");
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDefMessage(errorCode,msg);
if (("2002").equals(errorCode)||("2001").equals(errorCode)){
//项目中设计到Token过期重新登陆,Token过期未 2002 2001
// Utils.ShowTokenNewLogin(context);
}else {
//将错误信息返回到前端
callBack.onDefMessage(errorCode,msg);
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
//Put请求
@Override
public <T> void putRequest(Context context, String url, Map<String, String> map, final Class<T> tClass, final CallBack<T> callBack) {
}
//Delete请求
@Override
public <T> void deleteRequest(Context context, String url, Map<String, String> map, final Class<T> tClass, final CallBack<T> callBack) {
}
//直接返回Json数据
@Override
public void jsonRequest(Context context, String url, Map<String, String> map, final CallBack<String> callBack) {
}
}
PersistentCookieStore:
public class PersistentCookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "Cookies_Prefs";
private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<>();
//将持久化的cookies缓存到内存中 即map cookies
Map<String, ?> prefsMap = cookiePrefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
if (!cookies.containsKey(entry.getKey())) {
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
protected String getCookieToken(Cookie cookie) {
return cookie.name() + "@" + cookie.domain();
}
public void add(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
//将cookies缓存到内存中 如果缓存过期 就重置此cookie
if (!cookie.persistent()) {
if (!cookies.containsKey(url.host())) {
cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(url.host()).put(name, cookie);
} else {
if (cookies.containsKey(url.host())) {
cookies.get(url.host()).remove(name);
}
}
//讲cookies持久化到本地
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
prefsWriter.apply();
}
public List<Cookie> get(HttpUrl url) {
ArrayList<Cookie> ret = new ArrayList<>();
if (cookies.containsKey(url.host()))
ret.addAll(cookies.get(url.host()).values());
return ret;
}
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
return true;
}
public boolean remove(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
cookies.get(url.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(name)) {
prefsWriter.remove(name);
}
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.apply();
return true;
} else {
return false;
}
}
public List<Cookie> getCookies() {
ArrayList<Cookie> ret = new ArrayList<>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
/**
* cookies 序列化成 string
*
* @param cookie 要序列化的cookie
* @return 序列化之后的string
*/
protected String encodeCookie(SerializableOkHttpCookies cookie) {
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e) {
LogUtil.fussenLog().d("IOException in encodeCookie" + e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
/**
* 将字符串反序列化成cookies
*
* @param cookieString cookies string
* @return cookie object
*/
protected Cookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
} catch (IOException e) {
LogUtil.fussenLog().d("IOException in decodeCookie" + e);
} catch (ClassNotFoundException e) {
LogUtil.fussenLog().d("ClassNotFoundException in decodeCookie" + e);
}
return cookie;
}
/**
* 二进制数组转十六进制字符串
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* 十六进制字符串转二进制数组
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
SerializableOkHttpCookies:
public class SerializableOkHttpCookies implements Serializable {
private transient final Cookie cookies;
private transient Cookie clientCookies;
public SerializableOkHttpCookies(Cookie cookies) {
this.cookies = cookies;
}
public Cookie getCookies() {
Cookie bestCookies = cookies;
if (clientCookies != null) {
bestCookies = clientCookies;
}
return bestCookies;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookies.name());
out.writeObject(cookies.value());
out.writeLong(cookies.expiresAt());
out.writeObject(cookies.domain());
out.writeObject(cookies.path());
out.writeBoolean(cookies.secure());
out.writeBoolean(cookies.httpOnly());
out.writeBoolean(cookies.hostOnly());
out.writeBoolean(cookies.persistent());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
long expiresAt = in.readLong();
String domain = (String) in.readObject();
String path = (String) in.readObject();
boolean secure = in.readBoolean();
boolean httpOnly = in.readBoolean();
boolean hostOnly = in.readBoolean();
boolean persistent = in.readBoolean();
Cookie.Builder builder = new Cookie.Builder();
builder = builder.name(name);
builder = builder.value(value);
builder = builder.expiresAt(expiresAt);
builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
builder = builder.path(path);
builder = secure ? builder.secure() : builder;
builder = httpOnly ? builder.httpOnly() : builder;
clientCookies = builder.build();
}
}
搞定收工,以后用直接调用就可以。