Skip to content

Instantly share code, notes, and snippets.

@Sar777
Created June 26, 2017 22:45

Revisions

  1. Orion created this gist Jun 26, 2017.
    40 changes: 40 additions & 0 deletions AuthInterceptor.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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;
    }
    }
    13 changes: 13 additions & 0 deletions NetworkInterceptor.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    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();
    }
    }