天天看點

OkHttp請求 android 逾時時間

增加:


       
//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; 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, "伺服器異常,稍後再試");
                }
            });
}      

繼續閱讀