Reproducing WS frameworks

I have a problem calling WS.url () in play 2.3.3 with URLs that contain spaces. All other characters are all url encoded automatically, but not spaces. When I try to change all spaces to "% 20" WS converts it to "% 2520" due to the "%" character. With spaces, I have java.net.URISyntaxException: Invalid character in request. How can I handle this?

part of url query String:

 &input=/mnt/mp3/music/folder/01 - 23.mp3

      

The code looks like this:

Promise<JsonNode> jsonPromise = WS.url(url).setAuth("", "cube", WSAuthScheme.BASIC).get().map(
                new Function<WSResponse, JsonNode>() {
                    public JsonNode apply(WSResponse response) {
                        System.out.println(response.getBody());
                        JsonNode json = response.asJson();
                        return json;
                    }
                }
                );

      

+3


source to share


2 answers


You should "build" your url based on the way you use java.net.URL (which uses Play! WS for). WS.url () follows the same logic.

Using URLEncoder / Decoder is recommended for form data only. From JavaDoc:

"Note: the java.net.URI class does escaping its field component under certain circumstances. The recommended way to control URL encoding and decoding is to use java.net.URI and convert between the two using toURI () and URI.toURL (). The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which does not match the specified encoding scheme in RFC2396. "

So the solution is to use THIS :

WS.url(baseURL).setQueryString(yourQueryString);

      

Where:

  • baseURL

    is your schema + host + path etc.
  • yourQueryString

    ... well your request is String, but WITHOUT ?

    : input = / mnt / mp3 / music / folder / 01 - 23.mp3


Or, if you want a more flexible programmatic approach, THIS is :

WS.url(baseURL).setQueryParameter(param, value);

      

Where:

  • param

    is the name of the parameter in the String request
  • value

    - parameter value

If you need multiple parameters with values ​​in the request, you need to bind them by adding another one .setQueryParameter(...)

. This means that this approach is not very suitable for complex multiparameter query strings.


Hooray!

+3


source


If you check your console, you can see this is the exception: java.net.URISyntaxException: Illegal character in path at index ...

This is because the Java api is used to reproduce java.net.URL

(as you see here on line 47).

You can use java.net.URLEncoder to encode your url

WS.url("http://" + java.net.URLEncoder.encode("google.com/test me", "UTF-8"))

      



UPDATE

If you want an RFC 2396 compliant way, you can do this:

java.net.URI u = new java.net.URI(null, null, "http://google.com/test me",null);
System.out.println("encoded url " + u.toASCIIString()); 

      

0


source







All Articles