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}}