Я создала класс CookieInterceptor
, который извлекает cookie из первого ответа сервера и добавляет их для всех последующих запросов телефона:
public class CookieInterceptor implements Interceptor {
private static final String LOG_TAG = "TAG",
SET_COOKIE_TAG = "Set-Cookie",
COOKIE_TAG = "Cookie",
SESSION_ID_NAME = "JSESSIONID=";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = processRequest(request);
Response response = chain.proceed(request);
Log.e(LOG_TAG, "header size: " + request.headers().size());
for (String name : request.headers().names()) {
Log.e(LOG_TAG, "header name: " + name + ", value: " + request.headers().get(name));
}
response = processResponse(response);
return response;
}
//Extract cookies from the first server response
private Response processResponse(Response response) {
if (response.header(SET_COOKIE_TAG) != null) {
final List<String> cookieHeaders = response.headers(SET_COOKIE_TAG);
for (String cookieHeader : cookieHeaders) {
if (cookieHeader.contains(SESSION_ID_NAME)) {
String sessionId = cookieHeader.substring(11, cookieHeader.indexOf(';'));
App.setSessionId(sessionId);
Log.e(LOG_TAG, "extacted cookie: " + SESSION_ID_NAME + sessionId);
break;
}
}
}
return response;
}
//Add cookies for all subsequent requests
private Request processRequest(Request request) {
if(!request.url().toString().equals(App.getFirstUrl())) {
if (App.getSessionId() != null) {
request = request.newBuilder()
.addHeader(COOKIE_TAG, App.getSessionId())
.build();
Log.e(LOG_TAG, "added cookie: " + SESSION_ID_NAME + App.getSessionId());
}
}
return request;
}
}
В итоге в логах я вижу следующее.
Первый запрос от телефона:
--> POST http://host:8081/read
Content-Type: application/json; charset=UTF-8
Content-Length: 17
{"id":"FAE13980"}
--> END POST (28-byte body)
Первый ответ от сервера, куки с идентификатором сессии получены:
header size: 0
extacted cookie: JSESSIONID=A2B41558168583E9A30797228D0371FE
<-- 200 http://host:8081/read (321ms)
...
Set-Cookie: JSESSIONID=A2B41558168583E9A30797228D0371FE; Path=/; HttpOnly
...
<-- END HTTP (119-byte body)
Второй запрос от телефона:
--> POST http://host:8081/auth
Content-Type: application/json; charset=UTF-8
Content-Length: 36
{"id":"FAE13980","commandRs":["40"]}
--> END POST (79-byte body)
added cookie: JSESSIONID=A2B41558168583E9A30797228D0371FE
header size: 1
header name: Cookie, value: A2B41558168583E9A30797228D0371FE
По логам похоже, что идентификатор сессии добавляется к header-у запроса уже после того, как запрос был послан... Как это можно исправить?
P.S.: Для логирования я использую okhttp3.logging.HttpLoggingInterceptor
. Или же это HttpLoggingInterceptor неправильно логирует header-ы запроса?