首页 > 解决方案 > 改造:正在更改网址

问题描述

目前我在改造方面面临一些问题。我提供给RetrofitInstance第二个请求的 URL 正在更改。以下是代码:

object RetrofitClientInstance{

     private var retrofit: Retrofit? = null
     //private const val BASE_URL = "http://api.sample.com/req/";
     private const val BASE_URL = "http://test.sample.com/req/"
     private const val BASE_URL_VERSION = "v1/"


     fun getRetrofitInstance() : Retrofit {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL + BASE_URL_VERSION)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
        }
        return this!!.retrofit!!
    }

}

以下是interface针对不同 API 请求的方法:

class UserLoginResponseReceiver{

    interface GetDataService {

        @FormUrlEncoded
        @POST(UrlEndPoints.USER_LOGIN_BY_FACEBOOK)
        fun loginUserByFacebook(@Field("access_token") last: String): Call<FbLoginResponse>

        @GET(UrlEndPoints.ALL_POSTS)
        fun getAllPosts() : Call<AllPostsResponse>

    }
}

网址端点.kt

object UrlEndPoints {

   const val USER_LOGIN_BY_FACEBOOK = "user/auth/facebook"
   const val ALL_POSTS = "post"
}

对于第一个请求(loginUserByFacebook),我通过调试响应获得的 URL 是:

http://test.sample.com/req/v1/user/auth/facebook

这很好,工作完美。但是对于第二个请求(getAllPosts()),我得到了以下 URL:

http://test.sample.com/post

req/v1”部分被完全切断!结果我没有得到想要的回应。实际上这里有什么问题?请帮我。

标签: androidkotlinretrofit2

解决方案


我无法重现这一点,您应该尝试清理/重建您的项目,您在此处提供的代码没有错误。

这是我添加来测试它的代码:

class AllPostsResponse
class FbLoginResponse

fun main(args: Array<String>) {
    val service = RetrofitClientInstance.getRetrofitInstance()
                     .create(UserLoginResponseReceiver.GetDataService::class.java)
    val url = service.getAllPosts().request().url()
    println(url)
}

正如预期的那样,此处返回的 URL 如下所示:

http://test.sample.com/req/v1/post

推荐阅读