commons httpclient - Adding query string parameters to GET/POST request

前端 未结 6 2186
情深已故
情深已故 2020-12-04 23:38

I am using commons HttpClient to make an http call to a Spring servlet. I need to add a few parameters in the query string. So I do the following:

HttpReques         


        
6条回答
  •  醉话见心
    2020-12-05 00:00

    This is how I implemented my URL builder. I have created one Service class to provide the params for the URL

    public interface ParamsProvider {
    
        String queryProvider(List params);
    
        String bodyProvider(List params);
    }
    
    

    The Implementation of methods are below

    @Component
    public class ParamsProviderImp implements ParamsProvider {
        @Override
        public String queryProvider(List params) {
            StringBuilder query = new StringBuilder();
            AtomicBoolean first = new AtomicBoolean(true);
            params.forEach(basicNameValuePair -> {
                if (first.get()) {
                    query.append("?");
                    query.append(basicNameValuePair.toString());
                    first.set(false);
                } else {
                    query.append("&");
                    query.append(basicNameValuePair.toString());
                }
            });
            return query.toString();
        }
    
        @Override
        public String bodyProvider(List params) {
            StringBuilder body = new StringBuilder();
            AtomicBoolean first = new AtomicBoolean(true);
            params.forEach(basicNameValuePair -> {
                if (first.get()) {
                    body.append(basicNameValuePair.toString());
                    first.set(false);
                } else {
                    body.append("&");
                    body.append(basicNameValuePair.toString());
                }
            });
            return body.toString();
        }
    }
    
    

    When we need the query params for our URL, I simply call the service and build it. Example for that is below.

    Class Mock{
    @Autowired
    ParamsProvider paramsProvider;
     String url ="http://www.google.lk";
    // For the query params price,type
     List queryParameters = new ArrayList<>();
     queryParameters.add(new BasicNameValuePair("price", 100));
     queryParameters.add(new BasicNameValuePair("type", "L"));
    url = url+paramsProvider.queryProvider(queryParameters);
    // You can use it in similar way to send the body params using the bodyProvider
    
    }
    
    

提交回复
热议问题