okhttp3 post請求基本使用以及超時重連


我用真機調試的時候還挺坑的,一直報 failed to connect to /172.26.75.93 (port 8080) after 60000ms 的錯誤,沒找到原因,后來發現是防火牆不知道什么是時候給打開了。
所以千萬要注意下面兩點:

  • 關掉防火牆!
  • 確保手機和電腦在同一局域網下
    private int serversLoadTimes =0;
    private static final int maxLoadTimes =3; // 最大重連次數
    private OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS) // 設置連接超時時間
            .readTimeout(20, TimeUnit.SECONDS) // 設置讀取超時時間
            .build();
        serversLoadTimes = 0;
        RequestBody requestBody =
                new FormBody.Builder()
                        .add("phone", phone)
                        .add("password", password)
                        .build();
        Log.e(TAG, HttpPath.getUserLoginPath());
        Request req = new Request.Builder().url(HttpPath.getUserLoginPath()).post(requestBody).build();
        Call call = client.newCall(req);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失敗回調
                Log.e(TAG, "onFailure: " + e.getMessage());
                if(e instanceof SocketTimeoutException && serversLoadTimes < maxLoadTimes) // 如果超時並未超過指定次數,則重新連接
                {
                    serversLoadTimes++;
                    Log.e(TAG, "Reconnect: " + serversLoadTimes + " times");
                    client.newCall(call.request()).enqueue(this);
                }else {
                    e.printStackTrace();
                }

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功回調,當前線程為子線程,如果需要更新UI,需要post到主線程中

                boolean successful = response.isSuccessful();
                //響應消息頭
                Headers headers = response.headers();
                //響應消息體
                ResponseBody body = response.body();
                String content = response.body().string();
                //緩存控制
                CacheControl cacheControl = response.cacheControl();

                Log.e(TAG, response.protocol() + " " +response.code() + " " + response.message());
                for (int i = 0; i < headers.size(); i++) {
                    Log.e(TAG, headers.name(i) + ":" + headers.value(i));
                }

                Log.e(TAG, "onResponse: " + content);
            }
        });

Log 如下:

05-06 23:36:52.291 29860-29860/com.xl.travelassistant E/LoginActivity: http://172.26.75.93:8080/travel-assistant/user/login.do
05-06 23:36:52.975 29860-30187/com.xl.travelassistant E/LoginActivity: http/1.1 200 OK
05-06 23:36:52.975 29860-30187/com.xl.travelassistant E/LoginActivity: Server:Apache-Coyote/1.1
05-06 23:36:52.975 29860-30187/com.xl.travelassistant E/LoginActivity: Set-Cookie:JSESSIONID=1F191DABDD0B37DB98997DB436286C81; Path=/travel-assistant; HttpOnly
05-06 23:36:52.975 29860-30187/com.xl.travelassistant E/LoginActivity: Content-Type:application/json;charset=UTF-8
05-06 23:36:52.975 29860-30187/com.xl.travelassistant E/LoginActivity: Transfer-Encoding:chunked
05-06 23:36:52.975 29860-30187/com.xl.travelassistant E/LoginActivity: Date:Mon, 06 May 2019 15:36:53 GMT
05-06 23:36:52.977 29860-30187/com.xl.travelassistant E/LoginActivity: onResponse: okhttp3.internal.http.RealResponseBody@f8750ee
05-06 23:36:52.977 29860-30187/com.xl.travelassistant E/LoginActivity: onResponse: {"status":0,"msg":"登錄成功","data":{"id":1,"phone":"17806266949","username":"xlupc","password":"","createTime":1557027700000,"updateTime":1557128168000}}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM