首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >改进2-动态URL

改进2-动态URL
EN

Stack Overflow用户
提问于 2015-09-14 15:29:57
回答 4查看 163.7K关注 0票数 226

使用Retrofit 2,您可以在服务方法的注释中设置完整的URL,如:

代码语言:javascript
复制
public interface APIService {
  @GET("http://api.mysite.com/user/list")
  Call<Users> getUsers();
}

然而,在我的应用程序中,我的with服务的URL在编译时是未知的,应用程序在下载的文件中检索它们,所以我想知道如何使用Retrofit 2与完整的动态URL。

我尝试设置完整路径,如下所示:

代码语言:javascript
复制
public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path("fullUrl") fullUrl);
}

new Retrofit.Builder()
  .baseUrl("http://api.mysite.com/")
  .build()
  .create(APIService.class)
  .getUsers("http://api.mysite.com/user/list"); // this url should be dynamic
  .execute();

但是在这里,Retrofit没有看到路径实际上是一个完整的URL,并试图下载http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist

有什么建议我可以使用Retrofit这样的动态网址吗?

谢谢

EN

回答 4

Stack Overflow用户

发布于 2017-03-23 07:26:28

我只想替换url的一部分,使用这个解决方案,我不需要传递整个url,只需要传递动态部分:

代码语言:javascript
复制
public interface APIService {

  @GET("users/{user_id}/playlists")
  Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}
票数 176
EN

Stack Overflow用户

发布于 2015-12-03 23:29:55

在Retrofit 2.0.0-beta2版本中,如果您有一个服务从这个URL响应JSON:http://myhost/mypath

以下代码不起作用:

代码语言:javascript
复制
public interface ClientService {
    @GET("")
    Call<List<Client>> getClientList();
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList().execute();

但这是可以的:

代码语言:javascript
复制
public interface ClientService {
    @GET
    Call<List<Client>> getClientList(@Url String anEmptyString);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList("").execute();
票数 22
EN

Stack Overflow用户

发布于 2019-06-28 14:54:04

如果您已经设置了代码,并且不想在不同的接口上进行更改,请使用本link中描述的解决方案。要点是更新URL并重新创建Retrofit构建器的方法changeApiBaseUrl

代码语言:javascript
复制
public class ServiceGenerator {  
public static String apiBaseUrl = "http://futurestud.io/api";
private static Retrofit retrofit;

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(apiBaseUrl);

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

// No need to instantiate this class.
private ServiceGenerator() {
}

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

    builder = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(apiBaseUrl);
}

public static <S> S createService(Class<S> serviceClass, AccessToken token) {
    String authToken = token.getTokenType().concat(token.getAccessToken());
    return createService(serviceClass, authToken);
}

// more methods
// ...
}

您可以按如下方式使用它:

代码语言:javascript
复制
public class DynamicBaseUrlActivity extends AppCompatActivity {

public static final String TAG = "CallInstances";
private Callback<ResponseBody> downloadCallback;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file_upload);

    downloadCallback = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG, "server contacted at: " + call.request().url());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(TAG, "call failed against the url: " + call.request().url());
        }
    };

    // first request
    FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> originalCall = downloadService.downloadFileWithFixedUrl();
    originalCall.enqueue(downloadCallback);

    // change base url
    ServiceGenerator.changeApiBaseUrl("http://development.futurestud.io/api");

    // new request against new base url
    FileDownloadService newDownloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> newCall = newDownloadService.downloadFileWithFixedUrl();
    newCall.enqueue(downloadCallback);
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32559333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档