Skip to content

Instantly share code, notes, and snippets.

@Sar777
Created June 26, 2017 22:45
Show Gist options
  • Save Sar777/f7daaa0f9c0ad67def24dbd4a53d20bc to your computer and use it in GitHub Desktop.
Save Sar777/f7daaa0f9c0ad67def24dbd4a53d20bc to your computer and use it in GitHub Desktop.
OkHttp network interceptor for replace http status code.
public class AuthInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
// Handle only post requests
if (!request.method().equals("POST")) {
return chain.proceed(chain.request());
}
// Only login request
if (!request.url().toString().contains("/login")) {
return chain.proceed(chain.request());
}
Response response = chain.proceed(chain.request());
JSONObject jsonObject = new JSONObject();
try {
StringBuilder stringBuilder = new StringBuilder();
for (String header : response.headers("Set-Cookie")) {
stringBuilder.append(header).append(" ");
}
Document doc = Jsoup.parse(response.body().string());
Element element = doc.select("div.lite-center > p > span").first();
jsonObject.put("message", element != null ? element.text() : "Successful");
jsonObject.put("cookie", response.code() == 308 ? stringBuilder.toString().substring(0, stringBuilder.length() - 1) : "");
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
return response.newBuilder().body(body).build();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
}
public class NetworkInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (response.code() != 301) {
return response;
}
return response.newBuilder().code(308).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment