8

I would like to create a URI using apache class org.apache.http.client.utils.URIBuilder and I need to not encode query params to percent-encoding.

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.net.URI;


public class Main {
    public static void main(String[] args) throws Exception {

        RequestConfig config = RequestConfig.custom().build();

        HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config);

//        URI url = new URI("http://some-website.com/?range=10,20");
//        If url is created with the line above the comma "," is not encoded when sending the request
//        When you use URIBuilder the comma "," is converted to "%2C"

        URIBuilder uribuilder = new URIBuilder("http://some-website.com/");

        uribuilder.addParameter("range", "10,20");

        URI url = uribuilder.build();

        System.out.println("URL => " + url.toString());


        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getScheme());

        HttpClient client = builder.build();

        HttpRequestBase req = new HttpPost(url);


        HttpResponse httpResponse = client.execute(targetHost, req);

        HttpEntity entity = httpResponse.getEntity();

        String responseString = EntityUtils.toString(entity, "UTF-8");

        System.out.println(responseString);
        System.out.println("Finished");
    }
}

Is there a way to do that using the URIBuilder class like some flag I don't know?

I would appreciate other suggests (maybe better ways than my code) to accomplish this. But I can't send the characters in query string encoded.

Thanks in advance.

4
  • 4
    How about uribuilder.setCustomQuery("range=10,20");
    – Mafor
    Commented Dec 18, 2019 at 17:24
  • @Mafor Can I loop a Map<string, string> to add query strings using this method you refer? I mean, I would need to build the all the query string before doing this, right?
    – Bart
    Commented Dec 18, 2019 at 18:29
  • 1
    That's right, you won't be able to add parameters one by one anymore. But I don't think there is any other option if you want to use URIBuilder.
    – Mafor
    Commented Dec 18, 2019 at 19:48
  • Are you still having this issue. You can try to use URIBuilder.of(full_path). I tested it, seems working without encoded characters
    – macemers
    Commented Aug 18, 2023 at 6:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.