@@ -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