Skip to content

Instantly share code, notes, and snippets.

@Abdallah-Abdelazim
Last active May 9, 2021 13:44
Show Gist options
  • Save Abdallah-Abdelazim/445bbea12a33cd3fdec4fba4a56a2ec8 to your computer and use it in GitHub Desktop.
Save Abdallah-Abdelazim/445bbea12a33cd3fdec4fba4a56a2ec8 to your computer and use it in GitHub Desktop.
HttpsEverywhereInterceptor: An OkHttp interceptor to replace any HTTP scheme with HTTPS for outgoing network requests.
package com.example.network;
import androidx.annotation.NonNull;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* An OkHttp interceptor to replace any HTTP scheme with HTTPS for outgoing network requests URLs.
* <br>
* You should add this interceptor before any logging interceptors.
*
* @author Abdallah Abdelazim
*/
public class HttpsEverywhereInterceptor implements Interceptor {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request originalRequest = chain.request();
HttpUrl.Builder urlBuilder = originalRequest.url().newBuilder();
if (originalRequest.url().scheme().equalsIgnoreCase("http")) {
urlBuilder.scheme("https");
}
Request request = originalRequest.newBuilder()
.url(urlBuilder.build())
.build();
return chain.proceed(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment