如何在没有baseUrl的情况下设置Retrofit

F1s*_*her 17 java rest android retrofit

我的apiPath是完全动态的.我正在使用包含"ipAddress"和"SSLprotocol"等字段的项目.基于它们我可以建立我的网址:

private String urlBuilder(Server server) {
    String protocol;
    String address = "";

    if (AppTools.isDeviceOnWifi(activity)) {
        address = serverToConnect.getExternalIp();
    } else if (AppTools.isDeviceOnGSM(activity)) {
        address = serverToConnect.getInternalIp();
    }

    if (server.isShouldUseSSL()) {
        protocol = "https://";
    } else {
        protocol = "http://";
    }
    return protocol + address;
}
Run Code Online (Sandbox Code Playgroud)

所以我的协议+地址可以是:http:// + 192.168.0.01:8010 = http://192.168.0.01:8010

我想这样使用它:

@FormUrlEncoded
@POST("{fullyGeneratedPath}/json/token.php")
Observable<AuthenticationResponse> authenticateUser(
            @Path("fullyGeneratedPath") String fullyGeneratedPath,
            @Field("login") String login,
            @Field("psw") String password,
            @Field("mobile") String mobile);
Run Code Online (Sandbox Code Playgroud)

因此,authenticateUser的完整路径将是http://192.168.0.01:8010/json/token.php - 例如.

这意味着我不需要任何basePath,因为我自己创建整个basePath,具体取决于我想要连接的服务器.

我的改造设置是:

@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient okHttpClient,
            Converter.Factory converterFactory,
            AppConfig appConfig) {
    Retrofit.Builder builder = new Retrofit.Builder();
    builder.client(okHttpClient)
            .baseUrl(appConfig.getApiBasePath())
            .addConverterFactory(converterFactory)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

    return builder.build();
}
Run Code Online (Sandbox Code Playgroud)

如果我删除baseUrl然后我得到错误,该参数是必需的.所以我将apiBasePath设置为:

public String getApiBasePath() {
    return "";
}
Run Code Online (Sandbox Code Playgroud)

然后我在创建改造实例后立即收到错误:

java.lang.IllegalArgumentException: Illegal URL: 
Run Code Online (Sandbox Code Playgroud)

怎么解决?

Inv*_*rce 34

(新URL解析概念),您只需在post请求中指定整个路径.

此外,我们还可以在Retrofit 2.0中的@Post中声明一个完整的URL:

public interface APIService {

    @POST("http://api.nuuneoi.com/special/user/list")
    Call<Users> loadSpecialUsers();

}
Run Code Online (Sandbox Code Playgroud)

对于这种情况,将忽略基本URL.

  • 这是创建没有基本 url 的调用的方法,但问题是“如何在没有基本 url 的情况下设置 Retrofit?”。难道不一样吗? (2认同)

max*_*max 8

就这样使用

public interface UserService {  
    @GET
    public Call<ResponseBody> profilePicture(@Url String url);
}
Run Code Online (Sandbox Code Playgroud)

来源

  • 这是否仍然需要您使用基本 URL 设置 RetroFit(在此特定调用中会被忽略)?当我强制所有调用都将 URL 作为参数并删除基本 URL 时,它仍然抛出异常:/ (4认同)

ult*_*aon 8

对于 Retrofit 2,你无论如何都必须输入基本 url。如果不知道,那么你可以输入任何网址,通常情况下,使用http://localhost/.