添加queryparam OKHttp3

时间:2018-02-19 10:27:02

标签: android api get okhttp3

我正在向我的API提出GET请求,而cURL看起来像是:

curl -X GET "http://www.example.com/api/users?role=ROLE1&role=ROLE2&role=ROLE3&pag=0&num=0" -H "accept: application/json"

我尝试按照我的Android应用程序发出请求,但是" addQueryParameter"没有附加角色

public void getActors(String[] roles, final ApiManager.Callback<List<UsersDetails>> callbackUsers) throws JSONException{
      final String url = BuildConfig.BASE_AUTH_URL + "/users";

      HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
      httpBuilder.addQueryParameter("roles", "ROLE1");
      httpBuilder.addQueryParameter("roles", "ROLE2");
      httpBuilder.addQueryParameter("roles", "ROLE3");
      httpBuilder.addQueryParameter("pag", "0");
      httpBuilder.addQueryParameter("num", "0");


      Request request = new Request.Builder()
              .url(httpBuilder.build())
              .addHeader("Content-type", "application/json")
              .get()
              .build();
...
编辑:此更改的代码有效,但我从服务器获取空值。

每个GET中的角色总是相同的。 有人可以帮我理解我在哪里犯错误吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试okHttpBuilder和尽可能多的尝试。

FormBody.Builder builder = new FormBody.Builder();
for (String m : list) {
    builder.add("roles", m);
}

然后像这样使用它

url.post(body.build());

httpBuilder.addQueryParameter("roles"+[0], "ROLE1");
httpBuilder.addQueryParameter("roles"+[1], "ROLE1");