增加:
//okhttp
compile 'com.squareup.okhttp3:okhttp:3.3.0'
import okhttp3.Response; /** * http回調 * Created by gb on 2018/1/18. */ public interface HttpCallInterface { void onSucceedBack(Response response, String jsonString); void onFailBack(Response response); }工具:
import android.content.Context; import com.tywl.chatroom.JumpApplication; import com.tywl.chatroom.interfacecommon.HttpCallInterface; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * OkHttp請求 * Created by gb on 2018/1/23. */ public class OkHttpUtils {
/** * 設置連接超時時間 */ public final static int CONNECT_TIMEOUT = 60; /** * 設置讀取超時時間 */ public final static int READ_TIMEOUT = 100; /** * 設置寫的超時時間 */ public final static int WRITE_TIMEOUT = 60;private static OkHttpClient mOkHttpClient; /** * 請求類別 * * @param path 地址 * @param method get,post * @param context * @param callInterface 連接回調 */ public static void requestData(String path, String method, Context context, final HttpCallInterface callInterface) { LogUtils.d("path=" + path); if (!NetworkUtils.isNetworkAvailable(JumpApplication.getInstance())) { ToastUtils.showHint(context, "網絡已斷開,請檢查網絡設置"); return; } if (mOkHttpClient == null) { mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//設置連接超時時間 .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//設置讀取超時時間 .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//設置寫的超時時間 .build(); }Request.Builder requestBuilder = new Request.Builder().url(path); //可以省略,默認是GET請求 requestBuilder.method(method, null); Request request = requestBuilder.build(); Call mcall = mOkHttpClient.newCall(request); mcall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { LogUtils.d("onFailure=" + e.toString()); callInterface.onFailBack(null); } @Override public void onResponse(Call call, Response response) throws IOException { String str = response.body().string(); LogUtils.d("onResponse=" + str); if (response.isSuccessful()) { callInterface.onSucceedBack(response, str); } else { callInterface.onFailBack(response); } if (response.body() != null) { //關閉防止內存泄漏 response.body().close(); } } }); }
}
使用:private void requestCategory() { OkHttpUtils.requestData(HttpConstant.HOME_CATEGORY, HttpConstant.HTTP_METHOD_GET, this, new HttpCallInterface() { @Override public void onSucceedBack(Response response, String message) { SPUtils.put(CommonConstant.SP_KEY_HOME_CATEGORY, setDataColor(message)); } @Override public void onFailBack(Response response) { ToastUtils.showHint(WelcomeActivity.this, "服務器異常,稍後再試"); } }); }