java 如何通过OkHttp向HTTP GET请求添加查询参数?

pgccezyw  于 2023-01-07  发布在  Java
关注(0)|答案(7)|浏览(291)

我使用的是最新的okhttp版本:确定的http-2.3.0.jar文件
java中如何在okhttp中给GET请求添加查询参数?
我找到了一个关于android的related question,但是这里没有答案!

9avjhtql

9avjhtql1#

对于okhttp3:

private static final OkHttpClient client = new OkHttpClient().newBuilder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build();

public static void get(String url, Map<String,String>params, Callback responseCallback) {
    HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
    if (params != null) {
       for(Map.Entry<String, String> param : params.entrySet()) {
           httpBuilder.addQueryParameter(param.getKey(),param.getValue());
       }
    }
    Request request = new Request.Builder().url(httpBuilder.build()).build();
    client.newCall(request).enqueue(responseCallback);
}
2mbi3lxu

2mbi3lxu2#

这是我的拦截器

private static class AuthInterceptor implements Interceptor {

    private String mApiKey;

    public AuthInterceptor(String apiKey) {
        mApiKey = apiKey;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        HttpUrl url = chain.request().url()
                .newBuilder()
                .addQueryParameter("api_key", mApiKey)
                .build();
        Request request = chain.request().newBuilder().url(url).build();
        return chain.proceed(request);
    }
}
fcwjkofz

fcwjkofz3#

我终于完成了我的代码,希望下面的代码可以帮助大家。我首先使用
第一个月
然后将URL传递给Request requesthttp,希望它能有所帮助。

public class NetActions {

    OkHttpClient client = new OkHttpClient();

    public String getStudentById(String code) throws IOException, NullPointerException {

        HttpUrl httpUrl = new HttpUrl.Builder()
                .scheme("https")
                .host("subdomain.apiweb.com")
                .addPathSegment("api")
                .addPathSegment("v1")
                .addPathSegment("students")
                .addPathSegment(code) // <- 8873 code passthru parameter on method
                .addQueryParameter("auth_token", "71x23768234hgjwqguygqew")
                // Each addPathSegment separated add a / symbol to the final url
                // finally my Full URL is: 
                // https://subdomain.apiweb.com/api/v1/students/8873?auth_token=71x23768234hgjwqguygqew
                .build();

        System.out.println(httpUrl.toString());

        Request requesthttp = new Request.Builder()
                .addHeader("accept", "application/json")
                .url(httpUrl) // <- Finally put httpUrl in here
                .build();

        Response response = client.newCall(requesthttp).execute();
        return response.body().string();
    }
}
juud5qan

juud5qan4#

正如在另一个答案中提到的,okhttp v2.4提供了新的功能,使之成为可能。
See http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/HttpUrl.Builder.html#addQueryParameter-java.lang.String-java.lang.String-
当前版本的okhttp there is no method provided that will handle this for you无法实现这一点。
其次最好的方法是构建一个url字符串或URL对象(在java.net.URL中找到),其中包含您自己的查询,并将其传递给okhttp的请求构建器。

如您所见,Request.Builder可以接受String或URL。
有关如何构建url的示例可以在What is the idiomatic way to compose a URL or URI in Java?中找到

inkz8wg9

inkz8wg95#

到目前为止(okhttp2.4),HttpUrl.Builder现在有方法addQueryParameter和addEncodedQueryParameter。

fumotvh3

fumotvh36#

您可以从现有的HttoUrl创建newBuilder并在其中添加查询参数。

Request req = it.request()
    return chain.proceed(
        req.newBuilder()
            .url(
                req.url().newBuilder()
                .addQueryParameter("v", "5.60")
                .build());
    .build());
0x6upsns

0x6upsns7#

使用HttpUrl类的函数:

//adds the pre-encoded query parameter to this URL's query string
addEncodedQueryParameter(String encodedName, String encodedValue)

//encodes the query parameter using UTF-8 and adds it to this URL's query string
addQueryParameter(String name, String value)

更详细:https://stackoverflow.com/a/32146909/5247331

相关问题