|
@@ -1,5 +1,6 @@
|
|
|
package com.benyanyi.okhttp;
|
|
|
|
|
|
+import android.app.Application;
|
|
|
import android.content.Context;
|
|
|
|
|
|
import com.benyanyi.okhttp.config.HttpRequest;
|
|
@@ -7,6 +8,7 @@ import com.benyanyi.okhttp.type.RequestType;
|
|
|
import com.benyanyi.okhttp.util.FormatUtil;
|
|
|
|
|
|
import java.io.File;
|
|
|
+import java.lang.reflect.InvocationTargetException;
|
|
|
|
|
|
/**
|
|
|
* @author YanYi
|
|
@@ -17,15 +19,13 @@ import java.io.File;
|
|
|
public class OkHttpUtil {
|
|
|
|
|
|
private static OkHttpUtil instance;
|
|
|
- private static Context mContext;
|
|
|
|
|
|
public static File cacheFile;
|
|
|
|
|
|
- public static OkHttpUtil getInstance(Context context) {
|
|
|
+ public static OkHttpUtil getInstance() {
|
|
|
if (instance == null) {
|
|
|
instance = new OkHttpUtil();
|
|
|
}
|
|
|
- mContext = context;
|
|
|
return instance;
|
|
|
}
|
|
|
|
|
@@ -33,14 +33,44 @@ public class OkHttpUtil {
|
|
|
if (FormatUtil.isEmpty(url) || (url.indexOf("https:") != 0 && url.indexOf("http:") != 0)) {
|
|
|
throw new RuntimeException("url is not http or https");
|
|
|
}
|
|
|
- return new HttpRequest(mContext, url, false);
|
|
|
+ return new HttpRequest(getApplication(), url, false);
|
|
|
+ }
|
|
|
+
|
|
|
+ public RequestType url(Context context, String url) {
|
|
|
+ if (FormatUtil.isEmpty(url) || (url.indexOf("https:") != 0 && url.indexOf("http:") != 0)) {
|
|
|
+ throw new RuntimeException("url is not http or https");
|
|
|
+ }
|
|
|
+ return new HttpRequest(context, url, false);
|
|
|
}
|
|
|
|
|
|
public RequestType url(String url, boolean isCache) {
|
|
|
+ if (FormatUtil.isEmpty(url) || (url.indexOf("https:") != 0 && url.indexOf("http:") != 0)) {
|
|
|
+ throw new RuntimeException("url is not http or https");
|
|
|
+ }
|
|
|
+ return new HttpRequest(getApplication(), url, isCache);
|
|
|
+ }
|
|
|
+
|
|
|
+ public RequestType url(Context mContext, String url, boolean isCache) {
|
|
|
if (FormatUtil.isEmpty(url) || (url.indexOf("https:") != 0 && url.indexOf("http:") != 0)) {
|
|
|
throw new RuntimeException("url is not http or https");
|
|
|
}
|
|
|
return new HttpRequest(mContext, url, isCache);
|
|
|
}
|
|
|
|
|
|
+ private Application getApplication() {
|
|
|
+ Application application;
|
|
|
+ try {
|
|
|
+ application = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
|
|
|
+ } catch (IllegalAccessException e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ } catch (InvocationTargetException e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ } catch (NoSuchMethodException e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ } catch (ClassNotFoundException e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ return application;
|
|
|
+ }
|
|
|
+
|
|
|
}
|