quarks
quarks

Reputation: 35276

Encode String URL in Java

I have this code below that encodes a URL before it is send over the wire (email):

private static String urlFor(HttpServletRequest request, String code, String email, boolean forgot) {
    try {
        URI url = forgot
            ? new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), createHtmlLink(),
                    "code="+code+"&email="+email+"&forgot=true", null)
            : new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), createHtmlLink(),
                    "code="+code+"&email="+email, null);
        String s = url.toString();
        return s;
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}  

/**
 * Create the part of the URL taking into consideration if 
 * its running on dev mode or production
 * 
 * @return
 */
public static String createHtmlLink(){
    if (GAEUtils.isGaeProd()){
        return "/index.html#ConfirmRegisterPage;";
    } else {
        return "/index.html?gwt.codesvr=127.0.0.1:9997#ConfirmRegisterPage;";
    }
}

The problem with this is that the generated email looks like this:

http://127.0.0.1:8888/index.html%3Fgwt.codesvr=127.0.0.1:9997%23ConfirmRegisterPage;?code=fdc12e195d&[email protected]

The ? mark and # symbol is replaced with %3F and %23 where when the link is opened from the browser it will not open as it is incorrect.

What is the correct way to do this?

Upvotes: 0

Views: 238

Answers (2)

Rasmus Faber
Rasmus Faber

Reputation: 49629

You need to combine the query-parts of the url and add the fragment as the correct parameter.

Something like this should work:

private static String urlFor(HttpServletRequest request, String code, String email, boolean forgot) {
    try {
        URI htmlLink = new URI(createHtmlLink());
        String query = htmlLink.getQuery();
        String fragment = htmlLink.getFragment();
        fragment += "code="+code+"&email="+email;
        if(forgot){
            fragment += "&forgot=true";
        }
        URI url = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), htmlLink.getPath(),
                    query, fragment);
        String s = url.toString();
        return s;
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49372

You can use the Java API method URLEncoder#encode(). Encode the query parameters using the method.

A better API for doing this is the UriBuilder.

Upvotes: 1

Related Questions