gpt4 book ai didi

java - 如何在运行时更改 API Base Url(Retrofit、Android、Java)?

转载 作者:行者123 更新时间:2023-11-30 10:09:49 27 4
gpt4 key购买 nike

我需要在运行时更改基本 url。我有登录按钮,当登录按钮单击时,我被称为我的登录 api如下所示:

登录 api = http://192.168.0.61/api/authenticate

API_BASE_URL = http://192.168.0.61/api/

当我从第一个 api 获得成功响应时,我获得了用于更改 baseUrl 的客户端服务器 url。

CompanyUrlConfigEntity companyUrlConfigEntity = response.body();像下面这样:

字符串 clientUrl = companyUrlConfigEntity。 getBaseUrl();

                            clientUrl = http://192.168.0.238/api/

在这个项目中主要面向客户或公司。所以他们有自己的服务器。每个公司都使用了 20 多个 api。所以我需要更改基本 url。

我还在下面检查了更改基本 url 的链接:

https://futurestud.io/tutorials/retrofit-2-how-to-change-api-base-url-at-runtime-2

然后像这样修改代码

public static void changeApiBaseUrl(String newApiBaseUrl) {
API_BASE_URL = newApiBaseUrl;

builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new Gson()));
}

当我调试并检查我的 baseUrl 时,它正确显示如下:

API_BASE_URL =  http://192.168.0.238/api/



But when i call my customer api it shows the my first base url calling,
the url not changed.

expected customer api : http://192.168.0.238/api/customers
reality customer api : http://192.168.0.61/api/customers


I am also checked below link :

https://futurestud.io/tutorials/retrofit-2-how-to-use-dynamic-urls-for-requests

thats working , But each api need to pass fullPath url with each api like below:
@GET
public Call<ResponseBody> profilePicture(@Url String url);

But using this method , each api calling place i need to attach full path of url.

There is any other options? Please help me.

ServiceGenerator.class

    public class ServiceGenerator {

public static String API_BASE_URL = "http://192.168.0.61/api/";

private static Retrofit retrofit;

private static OkHttpClient.Builder httpClient = new
OkHttpClient.Builder();

private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new
Gson()));

private ServiceGenerator() {

}

public static void changeApiBaseUrl(String newApiBaseUrl) {
API_BASE_URL = newApiBaseUrl;

builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new Gson()));


}

public static Retrofit retrofit() {
return retrofit;
}
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}

public static <S> S createService(Class<S> serviceClass,
final String authToken,
final ProgressListener progressListener) {
if (authToken != null) {
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();

final String headerValue = AUTHORIZATION_TYPE + authToken;
Request request = original.newBuilder()
.header(AUTHORIZATION_HEADER_KEY, headerValue)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
}

addResponseProgressListener(progressListener);

if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new
HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
}


if (authToken != null) {
if (picasso == null) {
setUpPicasso(authToken);
}
}


OkHttpClient client = httpClient.build();
httpClient.connectTimeout(15, TimeUnit.SECONDS);
httpClient.readTimeout(2, TimeUnit.MINUTES);
httpClient.writeTimeout(2, TimeUnit.MINUTES);
retrofit = builder.client(client).build();

return retrofit.create(serviceClass);
}
}

登录 fragment .java

@OnClick(R.id.bt_login)
void onLogin() {

checkValidityOfUser();

}

private void checkValidityOfUser() {
final Login login = getLoginCredentials();

Call<CompanyUrlConfigEntity> callCheckValidity = dataProcessController.
getApiClient().
checkValidityOfUsers(login.getUsername());

callCheckValidity.enqueue(new Callback<CompanyUrlConfigEntity>() {
@Override
public void onResponse(Call<CompanyUrlConfigEntity> call,
Response<CompanyUrlConfigEntity> response) {


if (response.code() == 200) {

CompanyUrlConfigEntity companyUrlConfigEntity = response.body();

boolean status = companyUrlConfigEntity.isValidUser();

if (status) {

String baseUrls = companyUrlConfigEntity.
getBaseUrl();
baseUrls = baseUrls + "/api/";
ServiceGenerator.changeApiBaseUrl(baseUrls);
logins();
} else {

ToastHelper.show("please contact admin");

}


} else {

ToastHelper.show("" + response.code() + response.message());

}

}

@Override
public void onFailure(Call<CompanyUrlConfigEntity> call, Throwable t) {

ToastHelper.show("please contact admin");
}
});
}


private void logins() {
login = getLoginCredentials();
Call<Void> callLogin = dataProcessController.
getApiClient().
login(login);

callLogin.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {

if (response.code() == 200) {

} else if (response.code() == 401) {

}
}

@Override
public void onFailure(Call<Void> call, Throwable t) {

}
});
}

最佳答案

根据您的评论,我会说您正确地更改了构建器上的 API url,但您的第二次调用仍然使用 url 未更改的服务实例。

再多解释一下,据我了解,这是所有内容的执行方式:

  • 创建 fragment 时,将创建 apiClient 并指向第一个 url
  • 在第一次调用中使用 dataProcessController.getApiClient(),您将获得指向第一个 url 的服务,然后执行调用。
  • 当调用成功时,您从结果中读取新的 url 并使用该新 url 更新 ServiceGenerator。然后执行 logins() 方法。
  • 在该方法中,您调用 dataProcessController.getApiClient() 并使用它进行第二次调用。但是,由于您从未重做 apiClient = ServiceGenerator.createService(ApiClient.class);,您获得的 apiClient 实例仍然指向第一个 url,因为它没有被通知 url 已更改.

我在这里尝试的是将 DataProcessController 类中的方法 getApiClient() 更改为如下所示:

public ApiClient getApiClient() {
apiClient = ServiceGenerator.createService(ApiClient.class);
return apiClient;
}

看看这是否更好。

或者如果你不想在该函数内部重新生成服务,你也可以这样做:

public class DataProcessController { 
private ApiClient apiClient = null;

private DataProcessController() {
regenerateClient();
}

public ApiClient getApiClient() { return apiClient; }

// add this to regenerate the client whenever url changes
public void regenerateClient() {
apiClient = ServiceGenerator.createService(ApiClient.class);
}
}

然后,每次更改 url 时,请执行以下操作:

ServiceGenerator.changeApiBaseUrl(baseUrls);
dataProcessController.regenerateClient();

并且每次执行 dataProcessController.getApiClient()

时,您都应该得到一个指向正确 url 的客户端

关于java - 如何在运行时更改 API Base Url(Retrofit、Android、Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53059135/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com