@@ -13,33 +13,41 @@ class RespecifyUrlInterceptor : Interceptor {
13
13
val invocation = request.tag(Invocation ::class .java)
14
14
if (invocation != null ) {
15
15
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
+ }
17
19
}
18
20
return chain.proceed(request)
19
21
}
20
22
21
- private fun getNewHttpUrl (invocation : Invocation , originalHttpUrl : HttpUrl ): HttpUrl {
23
+ private fun getNewHttpUrl (invocation : Invocation , originalHttpUrl : HttpUrl ): HttpUrl ? {
22
24
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
+ }
23
30
var urlAnnotation = method.getAnnotation(Url ::class .java)
24
31
var portAnnotation = method.getAnnotation(Port ::class .java)
25
32
if (urlAnnotation == null && portAnnotation == null ) {
26
33
val klass = method.declaringClass
27
34
urlAnnotation = klass.getAnnotation(Url ::class .java)
28
35
portAnnotation = klass.getAnnotation(Port ::class .java)
29
36
}
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)
42
49
}
50
+ return newBuilder.build()
43
51
}
44
52
45
53
}
0 commit comments