Skip to content

Commit

Permalink
bug fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
Tear丶残阳 committed Jul 1, 2022
1 parent e58e133 commit 6844c82
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
2 changes: 1 addition & 1 deletion http/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ tasks.withType<KotlinCompile> {
}

dependencies {
implementation("com.j256.simplemagic:simplemagic:1.17")
api("com.j256.simplemagic:simplemagic:1.17")
compileOnly(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
compileOnly("com.squareup.retrofit2:retrofit:2.9.0")
compileOnly("com.squareup.okhttp3:okhttp:4.9.1")
Expand Down
36 changes: 22 additions & 14 deletions http/src/main/kotlin/cn/numeron/retrofit/RespecifyUrlInterceptor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,41 @@ class RespecifyUrlInterceptor : Interceptor {
val invocation = request.tag(Invocation::class.java)
if (invocation != null) {
val httpUrl = getNewHttpUrl(invocation, request.url)
request = request.newBuilder().url(httpUrl).build()
if (httpUrl != null) {
request = request.newBuilder().url(httpUrl).build()
}
}
return chain.proceed(request)
}

private fun getNewHttpUrl(invocation: Invocation, originalHttpUrl: HttpUrl): HttpUrl {
private fun getNewHttpUrl(invocation: Invocation, originalHttpUrl: HttpUrl): HttpUrl? {
val method = invocation.method()
val isSpecUrl = method.parameterAnnotations.flatten().contains(retrofit2.http.Url())
if (isSpecUrl) {
// 如果API方法通过`retrofit2.http.Url`注解指定了访问地址,则不处理
return null
}
var urlAnnotation = method.getAnnotation(Url::class.java)
var portAnnotation = method.getAnnotation(Port::class.java)
if (urlAnnotation == null && portAnnotation == null) {
val klass = method.declaringClass
urlAnnotation = klass.getAnnotation(Url::class.java)
portAnnotation = klass.getAnnotation(Port::class.java)
}
return when {
urlAnnotation != null -> {
val url = urlAnnotation.value.toHttpUrl()
originalHttpUrl.newBuilder().host(url.host).port(url.port).build()
}
portAnnotation != null -> {
val port = portAnnotation.value
originalHttpUrl.newBuilder().port(port).build()
}
else -> {
originalHttpUrl
}
if (urlAnnotation == null && portAnnotation == null) {
// 方法和类上均没有注解,则不处理
return null
}
val newBuilder = originalHttpUrl.newBuilder()
if (urlAnnotation != null) {
val httpUrl = urlAnnotation.value.toHttpUrl()
newBuilder.host(httpUrl.host).port(httpUrl.port)
}
if (portAnnotation != null) {
// Port和Url可同时存在,但是Url中的端口将不生效。
newBuilder.port(portAnnotation.value)
}
return newBuilder.build()
}

}

0 comments on commit 6844c82

Please sign in to comment.