android - 是否可以使用 OkHttp 设置占位符路径参数

标签 android okhttp

我有一个网址 http://example.com/{x}/push/{y}我正在使用 OkHttp curl 它。

final HttpUrl httpUrl = HttpUrl
                .parse("http://example.com/{x}/push/{y}")
                .newBuilder()
                ???
                .build();

是否可以设置这些{x}{y}路径参数?
我可以看到像 addPathSegment 这样的方法这在某种程度上是相关的,但不是我想要的。

最佳答案

这是一种可以帮助您入门的技术。

HttpUrl template = HttpUrl.parse("http://example.com/{a}/b/{c}");
HttpUrl.Builder builder = template.newBuilder();

for (int i = 0; i < template.pathSegments().size(); i++) {
  String parameter = template.pathSegments().get(i);
  String replacement = null;

  if (parameter.equals("{a}")) {
    replacement = "foo";
  } else if (parameter.equals("{c}")) {
    replacement = "bar";
  }

  if (replacement != null) {
    builder.setPathSegment(i, replacement);
  }
}

HttpUrl url = builder.build();

关于android - 是否可以使用 OkHttp 设置占位符路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751755/

相关文章:

android - 实际类型别名 'ApplicationContext' 没有对应的预期声明

javascript - Android Google map 应用与使用 Android WebView 查看网页中嵌入的 Google map

android - 改造更改一次 api 调用的读取超时

android - OkHttpClient "open"方法在 v2.0 中丢失

android - 如何使用 Retrofit 和 OKHttp 在下一次请求时使缓存路由无效/强制更新?

android - 停止服务内的线程

android - phonegap 应用程序的文档查看器

android - Flutter 从 Assets 文件夹中读取所有文件

java - 获取错误 java.lang.IllegalArgumentException : unexpected url

OkHttp 3 客户端如何为故障转移指定备用地址?