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

问题描述 投票:13回答:6

我的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;
}

所以我的协议+地址可以是: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);

因此,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();
}

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

public String getApiBasePath() {
    return "";
}

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

java.lang.IllegalArgumentException: Illegal URL: 

怎么解决?

java android rest retrofit
6个回答
32
投票

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

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

public interface APIService {

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

}

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


2
投票

就像这样用

public interface UserService {  
    @GET
    public Call<ResponseBody> profilePicture(@Url String url);
}

source


0
投票

如果您可以在每次要进行api调用时创建新的RestAdapter实例,则可以使用基本URL作为参数创建新的适配器。

Using absolute URLs with Retrofit


0
投票

是的,你可以做到。我这样做了:

public APIHelper(BaseActivity activity) {

    String url = Common.getAPIUrl();

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(url)
            .build();

    methods = restAdapter.create(IAppService.class);
}

基本上,一旦知道了端点网址,就需要创建改造对象。我想不再需要解释,因为代码是自我解释的。

假设只有基本网址发生了变化。


0
投票

我的方式使用改造

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.10.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.8'
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

在这里,我有一个通用类,里面我有我的方法

public static AppServiceApi setMyRetrofit(){
    Retrofit retrofit = null;
    AppServiceApi appServices = null;
    if (retrofit == null){
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();                                                                                  //
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(getClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        appServices = retrofit.create(AppServiceApi.class);
    }
    return appServices;
}

public static OkHttpClient getClient(){
    HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            /*.connectTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)*/.build();
    return client;
}

其中AppServiceApi接口具有我的所有结束URL和方法类型


0
投票

使用Retrofit 2,无论如何都必须放置基本URL。如果它不知道那么你可以放任何网址,通常,使用http://localhost/是好的。

© www.soinside.com 2019 - 2024. All rights reserved.