-
-
Notifications
You must be signed in to change notification settings - Fork 188
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
67 additions
and
8 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
app/src/main/java/per/goweii/wanandroid/http/GoweiiHostInterceptor.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package per.goweii.wanandroid.http | ||
|
||
import android.net.Uri | ||
import okhttp3.HttpUrl | ||
import okhttp3.Interceptor | ||
import okhttp3.Response | ||
import java.io.IOException | ||
|
||
class GoweiiHostInterceptor : Interceptor { | ||
companion object { | ||
private const val GOWEII_HOST = "goweii" | ||
|
||
private const val GITEE_PAGE_SERVER_BASE_URL = "https://goweii.gitee.io/wanandroidserver" | ||
private const val GITEE_RAW_SERVER_BASE_URL = "https://gitee.com/goweii/WanAndroidServer/raw/master" | ||
} | ||
|
||
override fun intercept(chain: Interceptor.Chain): Response { | ||
val request = chain.request() | ||
|
||
val httpUrl = request.url() | ||
if (httpUrl.host() != GOWEII_HOST) { | ||
return chain.proceed(request) | ||
} | ||
|
||
HttpUrl.parse(GITEE_PAGE_SERVER_BASE_URL) | ||
?.let { chain.tryWithBaseUrl(it) } | ||
?.takeIf { it.isSuccessful } | ||
?.let { return it } | ||
|
||
HttpUrl.parse(GITEE_RAW_SERVER_BASE_URL) | ||
?.let { chain.tryWithBaseUrl(it) } | ||
?.takeIf { it.isSuccessful } | ||
?.let { return it } | ||
|
||
throw IOException("Unknown goweii host.") | ||
} | ||
|
||
private fun Interceptor.Chain.tryWithBaseUrl(baseUrl: HttpUrl): Response { | ||
val httpUrl = request().url().replaceWithBaseUrl(baseUrl) | ||
return proceed(request().newBuilder().url(httpUrl).build()) | ||
} | ||
|
||
private fun HttpUrl.replaceWithBaseUrl(baseUrl: HttpUrl): HttpUrl { | ||
val uriBuilder = Uri.parse(baseUrl.toString()).buildUpon() | ||
encodedPathSegments().forEach { uriBuilder.appendEncodedPath(it) } | ||
uriBuilder.encodedQuery(encodedQuery()) | ||
val uri = uriBuilder.build() | ||
return HttpUrl.parse(uri.toString())!! | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters