package com.hsz.com.cc.OKHTTP;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import com.google.gson.Gson;
import com.hsz.com.cc.MainActivity;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class okhttp {
public static okhttp instance;
private OkHttpClient client;
private Handler handler=new Handler();
//判断网络状态
public static Boolean iswork(MainActivity mainActivity){
ConnectivityManager manager= (ConnectivityManager) mainActivity.getSystemService(mainActivity.CONNECTIVITY_SERVICE);
//获取网路哦状态
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
if (activeNetworkInfo !=null){
return activeNetworkInfo.isAvailable();
}
return false;
}
private okhttp() {
client= new OkHttpClient.Builder()
.writeTimeout(5000,TimeUnit.MILLISECONDS)
.readTimeout(5000,TimeUnit.MILLISECONDS)
.connectTimeout(5000,TimeUnit.MILLISECONDS)
.addInterceptor(new HeaderInterptor())
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
if (message.startsWith("{") || message.startsWith("[")){
com.orhanobut.logger.Logger.t("=====").json(message);
}else{
com.orhanobut.logger.Logger.t("=====").d(message);
}
}
}).setLevel(HttpLoggingInterceptor.Level.BODY)).build();
}
public static okhttp getInstance(){
if (instance ==null){
instance=new okhttp();
}
return instance;
}
public void Doget(String url, final Class clazz, final NetCallBack netCallBack){
client = new OkHttpClient();
Request build = new Request.Builder().url(url).get().build();
Call call=client.newCall(build);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Gson gson=new Gson();
final Object o = gson.fromJson(string, clazz);
handler.post(new Runnable() {
@Override
public void run() {
netCallBack.Success(o);
}
});
}
});
}
public interface NetCallBack{
public void Success(Object object);
public void Errot();
}
}
package com.hsz.com.cc.OKHTTP;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class HeaderInterptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder();
builder.addHeader("sessionId","15551491640981765");
builder.addHeader("userId","1765");
Log.i("cv","Sadsad");
Response proceed = chain.proceed(request);
return proceed;
}
}