2

So I have a URL which is

String url = request.getRequestURL()+"?"+request.getQueryString();

There is a parameter Custom="true", which i want to remove before i store it in url. Is there any efficient way to do this, without using regex.

Example - 

 http://myhost:8080/people?lastname=Fox&age=30&Custom=true&verified=yes

 request.getQueryString();  // "lastname=Fox&age=30&Custom=true&verified=yes"

Desired o/p - lastname=Fox&age=30&verified=yes
2
  • please provide example value of queryString Commented Mar 15, 2019 at 10:04
  • 1
    request.getQueryString().replace("Custom=true&", "") may be? Commented Mar 15, 2019 at 10:16

3 Answers 3

1

Just replace Custom=true with empty String

query = query.replace("Custom=true&",""); 
Sign up to request clarification or add additional context in comments.

3 Comments

I guess you did not understand the question, request.getQueryString() already returns string after ?. from that resulting string which is lastname=Fox&age=30&Custom=true&verified=yes" , I want to remove Custom=true
It will replace otherCustom=true& too
Parameters are unique so that will not be an issue.
0

If you want to replace exact match,below code will work.

String url = "http://myhost:8080/people?lastname=Fox&age=30&Custom=true&verified=yes";
    String newUrl = "";
    String[] splits = url.split("&");
    for(String split : splits) {
        if(!"Custom=true".equals(split)) {
            newUrl = newUrl+"&"+split;
        }
    }

1 Comment

This approach doesn't work if "Custom" is the only parameter in query string
0

Here's a solution that relies on Java 8 Streaming API:

    StringBuffer requestUrl = request.getRequestURL();
    String queryString = request.getQueryString();

    String[] queryStringParts = queryString.split("&");

    String newQueryString = Stream.of(queryStringParts)
            .filter(p -> !p.equals("Custom=true"))
            .collect(Collectors.joining("&"));

    String newUrl = StringUtils.hasText(newQueryString) ?
            requestUrl.append("?").append(newQueryString).toString() :
            requestUrl.toString();

Also the fact that request url and query string are initially separate (as stated in the question) actually helps.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.