Skip to content

Commit 6844c82

Browse files
author
Tear丶残阳
committed
bug fix.
1 parent e58e133 commit 6844c82

File tree

2 files changed

+23
-15
lines changed

2 files changed

+23
-15
lines changed

http/build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ tasks.withType<KotlinCompile> {
1515
}
1616

1717
dependencies {
18-
implementation("com.j256.simplemagic:simplemagic:1.17")
18+
api("com.j256.simplemagic:simplemagic:1.17")
1919
compileOnly(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
2020
compileOnly("com.squareup.retrofit2:retrofit:2.9.0")
2121
compileOnly("com.squareup.okhttp3:okhttp:4.9.1")

http/src/main/kotlin/cn/numeron/retrofit/RespecifyUrlInterceptor.kt

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,33 +13,41 @@ class RespecifyUrlInterceptor : Interceptor {
1313
val invocation = request.tag(Invocation::class.java)
1414
if (invocation != null) {
1515
val httpUrl = getNewHttpUrl(invocation, request.url)
16-
request = request.newBuilder().url(httpUrl).build()
16+
if (httpUrl != null) {
17+
request = request.newBuilder().url(httpUrl).build()
18+
}
1719
}
1820
return chain.proceed(request)
1921
}
2022

21-
private fun getNewHttpUrl(invocation: Invocation, originalHttpUrl: HttpUrl): HttpUrl {
23+
private fun getNewHttpUrl(invocation: Invocation, originalHttpUrl: HttpUrl): HttpUrl? {
2224
val method = invocation.method()
25+
val isSpecUrl = method.parameterAnnotations.flatten().contains(retrofit2.http.Url())
26+
if (isSpecUrl) {
27+
// 如果API方法通过`retrofit2.http.Url`注解指定了访问地址,则不处理
28+
return null
29+
}
2330
var urlAnnotation = method.getAnnotation(Url::class.java)
2431
var portAnnotation = method.getAnnotation(Port::class.java)
2532
if (urlAnnotation == null && portAnnotation == null) {
2633
val klass = method.declaringClass
2734
urlAnnotation = klass.getAnnotation(Url::class.java)
2835
portAnnotation = klass.getAnnotation(Port::class.java)
2936
}
30-
return when {
31-
urlAnnotation != null -> {
32-
val url = urlAnnotation.value.toHttpUrl()
33-
originalHttpUrl.newBuilder().host(url.host).port(url.port).build()
34-
}
35-
portAnnotation != null -> {
36-
val port = portAnnotation.value
37-
originalHttpUrl.newBuilder().port(port).build()
38-
}
39-
else -> {
40-
originalHttpUrl
41-
}
37+
if (urlAnnotation == null && portAnnotation == null) {
38+
// 方法和类上均没有注解,则不处理
39+
return null
40+
}
41+
val newBuilder = originalHttpUrl.newBuilder()
42+
if (urlAnnotation != null) {
43+
val httpUrl = urlAnnotation.value.toHttpUrl()
44+
newBuilder.host(httpUrl.host).port(httpUrl.port)
45+
}
46+
if (portAnnotation != null) {
47+
// Port和Url可同时存在,但是Url中的端口将不生效。
48+
newBuilder.port(portAnnotation.value)
4249
}
50+
return newBuilder.build()
4351
}
4452

4553
}

0 commit comments

Comments
 (0)