改造@Url不会覆盖BaseUrl

时间:2018-07-17 15:08:34

标签: android kotlin network-programming retrofit2 restful-architecture

嗨,我正在尝试从一个特定的api调用中覆盖baseUrl,当使用@Url作为api方法的参数时,它似乎不起作用。

下面是我的Api类方法

@POST
    fun getUserDetails(@Body body: request, @Url authUrl : String): Single<Response<ResponseData>>

标定并发出请求的代码

 private fun getApi(): Api {
        val gson = GsonBuilder().setLenient().create()
        val httpClient = myNetworkHelper.createHttpClient()
        val retrofit = Retrofit.Builder()
                .baseUrl("http://defaultBaseUrl")
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()

        return retrofit.create(Api::class.java)
    }

 override fun getUserDetails(someRequestData, "http://dynamic/getuserDetails): Single<Response<ResponseData>> {
        return getApi().getUserDetails(body, url)
    }

以上结果导致对此网址的请求

http://defaultBaseUrl/http://dynamic/getuserDetails

代替:

http://dynamic/getuserDetails

2 个答案:

答案 0 :(得分:1)

这是翻新@GET批注中的文档:

@Documented 
@Target(METHOD) 
@Retention(RUNTIME) 
public @interface GET {   
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
* <p>    
* See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how    
* this is resolved against a base URL to create the full endpoint URL.
*/   
    String value() default ""; 
}

因此,@Url应该作为第一个参数放置,所以我认为这会起作用:

@POST
fun getUserDetails(@Url authUrl : String, @Body body: request): Single<Response<ResponseData>>

答案 1 :(得分:1)

我在本地进行了测试,实际上我已经能够覆盖Retrofit实例中设置的基本URL。

以下是API:

public interface Api {

    @POST
    Call<Void> fakeService(@Url String url);
}

这是“客户”:

public class Main {

    public static void main(String[] args) throws IOException {
        // Use the HttpLogginInterceptor to check what's the real call
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(interceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.foo.com/")
                .client(client)
                .build();

        Api api = retrofit.create(Api.class);
        Call<Void> call = api.fakeService("http://www.example.com");
        call.execute();
    }
}

结果是:

Jul 18, 2018 12:28:54 PM okhttp3.internal.platform.Platform log
INFO: --> POST http://www.example.com/ (0-byte body)
Jul 18, 2018 12:28:55 PM okhttp3.internal.platform.Platform log
INFO: <-- 200 OK http://www.example.com/ (366ms, unknown-length body)