Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add query parameters to a HTTP GET request by OkHttp?

I am using the latest okhttp version: okhttp-2.3.0.jar

How to add query parameters to GET request in okhttp in java ?

I found a related question about android, but no answer here!

like image 206
Jerikc XIONG Avatar asked May 09 '15 16:05

Jerikc XIONG


People also ask

How do you add parameters in GET request?

To do http get request with parameters in Angular, we can make use of params options argument in HttpClient. get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.

What is OkHttp used for?

What is OkHttp? OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.

Does request URI include query string?

There is no protocol information given in URI. It contains components such as protocol, domain, path, hash, query string, etc.

How do I create an OkHttp client?

Customize Your Client With newBuilder() You can customize a shared OkHttpClient instance with newBuilder. This builds a client that shares the same connection pool, thread pools, and configuration. Use the builder methods to add configuration to the derived client for a specific purpose.


1 Answers

For 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); } 
like image 191
Yun CHEN Avatar answered Oct 16 '22 21:10

Yun CHEN