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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34842390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:26:19  来源:igfitidea点击:

How to setup Retrofit with no baseUrl

javaandroidrestretrofit

提问by F1sher

My apiPath is fully dynamic. I am having items containing fields such us "ipAddress" and "SSLprotocol". Based on them I can build my url:

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

So my protocol + address can be: http:// + 192.168.0.01:8010 = http://192.168.0.01:8010

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

And I would like to use it like that:

我想这样使用它:

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

So full path for authenticateUser would be http://192.168.0.01:8010/json/token.php- for example.

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

That means I don't need any basePath because I create whole basePath myself depending on server I want to connect to.

这意味着我不需要任何 basePath,因为我根据要连接的服务器自己创建了整个 basePath。

My retrofit setup is:

我的改造设置是:

@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();
}

If I remove baseUrl then I get error that this parameter is required. So I set my apiBasePath to:

如果我删除 baseUrl 那么我会得到这个参数是必需的错误。所以我将我的 apiBasePath 设置为:

public String getApiBasePath() {
    return "";
}

And then I get error instantly after I create retrofit instance:

然后我在创建改造实例后立即出错:

java.lang.IllegalArgumentException: Illegal URL: 

How to solve it?

如何解决?

回答by Inverce

From source(New URL resolving concept) you can simply specify whole path in post request.

新 URL 解析概念),您可以简单地在发布请求中指定整个路径。

Moreover we also can declare a full URL in @Post in Retrofit 2.0:

public interface APIService {

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

}

Base URL will be ignored for this case.

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

public interface APIService {

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

}

在这种情况下,基本 URL 将被忽略。

回答by max

just use like this

就这样使用

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

source

来源

回答by ultraon

With Retrofit 2 you have to put base url anyway. If it is not known then you just can put any url, usually, it is good to use http://localhost/.

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

回答by TheoKanning

If you're okay with creating a new RestAdapterinstance each time you want to make an api call, you could create a new adapter with the base url as a paramter.

如果RestAdapter每次想要进行 api 调用时都可以创建一个新实例,则可以创建一个新的适配器,并将基本 url 作为参数。

Using absolute URLs with Retrofit

在 Retrofit 中使用绝对 URL

回答by Irfan Raza

Yes you can do. I have done like this:

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

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);
}

Basically you need to create object of retrofit once you have known the endpoint url. I guess no more explanation is needed as code is self explanatory.

基本上,您需要在知道端点 url 后创建改造对象。我想不需要更多解释,因为代码是不言自明的。

Assuming that only base url is getting changed.

假设只有基本 url 被更改。

回答by Tanmay Sahoo

My way to use retrofit

我使用改造的方式

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'

And here i have a generic class and inside i have my method

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

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

where AppServiceApi interface have all my end urls and method type

其中 AppServiceApi 接口包含我所有的结束网址和方法类型