用参数改造baseUrl

时间:2017-07-16 10:03:45

标签: android retrofit retrofit2

我从服务器获取一个URL,其参数如下:

http://example/?p1=a&p2=b

这将是我将发送请求的服务器地址。

当我使用以下代码进行新的改造时。

retrofit.newBuilder().baseUrl(url).build();

拦截器

Request oldRequest = chain.request();
Logger.e("url:" + oldRequest.url());

日志:

url:http://example/

但我想将 baseUrl 设为:

http://example/?p1=a&p2=b

http://example/

那么是否有一些方法可以使baseUrl具有参数?

2 个答案:

答案 0 :(得分:0)

尝试以下操作,这是您的生成器类,可能看起来像这样。

public class ServiceGenerator {  
    public static String apiBaseUrl = "http://example/";
    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
    // ...
}

之后,您可以在活动或片段中以下列方式使用它

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://example/?p1=a&p2=b");

        // new request against new base url
        FileDownloadService newDownloadService = ServiceGenerator.create(FileDownloadService.class);
        Call<ResponseBody> newCall = newDownloadService.downloadFileWithFixedUrl();
        newCall.enqueue(downloadCallback);
    }
}

有关详情,请查看this

答案 1 :(得分:0)

你需要使用HttpUrl

*argv