Как использовать запрос и перехватчик ответа одновременно с тем, как я использовал следующий фрагмент кода для перехватчика запроса и ответа.
Для перехвата запроса:
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody oldBody = request.body();
if(request.method().equalsIgnoreCase("POST")){
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(MainActivity.TAG,"original req "+strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
String strNewBody = "data="+Encryption.encryptString(URLDecoder.decode(strOldBody).replace("data=",""));//EncryptionInterceptor.encryptString(strOldBody);
Log.i(MainActivity.TAG,"strNewBody "+strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(MainActivity.TAG,"content type is "+body.contentType().toString());
Log.i(MainActivity.TAG,"content length is "+String.valueOf(body.contentLength()));
Log.i(MainActivity.TAG,"method is "+request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
}
return chain.proceed(request);
}
Для перехватчика ответа:
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request();
Response response = chain.proceed(request);
try {
final String responseString = new String(response.body().bytes() );
Log.i(MainActivity.TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
Log.i(MainActivity.TAG, "Response edited: " + newResponseString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), newResponseString))
.build();
}catch (Exception ex){
return response;
}
}