依赖:compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
权限: <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class HttpUtil {
private static volatile HttpUtil httpUtil;
private final OkHttpClient client;
private Context context;
private Handler handler = new Handler(Looper.getMainLooper());
private HttpUtil(Context context) {
//缓存目录
File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
int cacheSize = 10 * 1024 * 1024;
//拦截器
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(logging)
// .addNetworkInterceptor(new CacheInterceptor())
// .writeTimeout(20, TimeUnit.SECONDS)
// .readTimeout(20, TimeUnit.SECONDS)
// .cache(new Cache(sdcache,cacheSize))
.build();
this.context = context;
}
public static HttpUtil getInstance(Context context) {
if (httpUtil == null) {
synchronized (HttpUtil.class) {
if (httpUtil == null) {
httpUtil = new HttpUtil(context);
}
}
}
return httpUtil;
}
public void doPost(String url, Map<String, String> params, final Class clazz, final OnNetListener onNetListener) {
//网络判断
if (!NetWorkUtil.isNetworkAvailable(context)) {
Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
return;
}
if (params != null && params.size() > 0) {
FormBody.Builder builder = new FormBody.Builder();
params.put("client", "android");
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
FormBody formBody = builder.build();
Request request = new Request.Builder().url(url).post(formBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final BaseBean baseBean = (BaseBean) new Gson().fromJson(response.body().string(), clazz);
int code = baseBean.getCode();
if (code == 200) {
handler.post(new Runnable() {
@Override
public void run() {
try {
onNetListener.onSuccess(baseBean);
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else if (code == 400) {
} else if (code == 300) {
}
}
});
}
}
public void download(String url, Callback callback) {
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
public void doGet(String url, final Class clazz, final OnNetListener onNetListener) {
//网络判断
if (!NetWorkUtil.isNetworkAvailable(context)) {
Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
return;
}
Request.Builder builder = new Request.Builder();
builder.url(url);
final Request request = builder.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
onNetListener.onError(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz);
int code = baseBean.getCode();
if (code == 200) {
handler.post(new Runnable() {
@Override
public void run() {
try {
onNetListener.onSuccess(baseBean);
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else if (code == 400) {
} else if (code == 300) {
}
}
});
}
/**
* @param url
* @param params
* @param header
* @param clazz
* @param onNetListener
*/
public void doGet(String url, HashMap<String, String> params, HashMap<String, String> header, final Class clazz, final OnNetListener onNetListener) {
//网络判断
if (!NetWorkUtil.isNetworkAvailable(context)) {
Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
return;
}
Request.Builder builder = new Request.Builder();
if (params != null && params.size() > 0) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(url);
sb.append("?");
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
}
url = sb.toString();
}
builder.url(url);
//添加请求头
if (params != null && header.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
final Request request = builder.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
onNetListener.onError(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz);
int code = baseBean.getCode();
if (code == 200) {
handler.post(new Runnable() {
@Override
public void run() {
try {
onNetListener.onSuccess(baseBean);
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else if (code == 400) {
} else if (code == 300) {
}
}
});
}
/**
* 上传
*
* @param url
* @param fileName
*/
public void uploadFile(String url, String fileName) {
String file = Environment.getExternalStorageState() + "/" + fileName;
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//创建RequestBody 设置类型等
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", fileName, fileBody).build();
Request request = new Request.Builder().url(url).post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
/**
* 下载
*
* @param url
*/
public void download(String url) {
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
}
public class NetWorkUtil {
// check all network connect, WIFI or mobile
public static boolean isNetworkAvailable(final Context context) {
boolean hasWifoCon = false;
boolean hasMobileCon = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfos = cm.getAllNetworkInfo();
for (NetworkInfo net : netInfos) {
String type = net.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
if (net.isConnected()) {
hasWifoCon = true;
}
}
if (type.equalsIgnoreCase("MOBILE")) {
if (net.isConnected()) {
hasMobileCon = true;
}
}
}
return hasWifoCon || hasMobileCon;
}
}
public class BaseActivity extends AppCompatActivity {
private LinkedList<Activity> list = new LinkedList<>();
protected HttpUtil httpUtil;
private ProgressDialog dialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list.add(this);
httpUtil = HttpUtil.getInstance(this);
}
protected void toast(String str) {
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public void finshAll() {
for (Activity ac : list) {
if (!ac.isFinishing()) {
ac.finish();
}
}
}
/**
* 显示进度条
*/
protected void showPd() {
dialog = new ProgressDialog(this);
dialog.setMessage("正在加載...");
dialog.show();
}
/**
* 关闭进度条
*/
protected void dismissPd() {
if (dialog != null && !this.isFinishing()) {
dialog.dismiss();
}
}
}
public class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Logger.i(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Logger.i(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}