Passing url parameters :
Consider creating a route like: http://host:port/url ( e.g. http://localhost:4567/https://finance.yahoo.com/q/ks?s=VNJTX+Key+Statistics )
whereas the black url portion you want to pass as parameter.
This can be done very easily using splats (http://sparkjava.com/documentation.html).
With the following code in your route:
- port(8081);//lets start our server on port 8081
- get("/", (request, response) -> "Welcome to HelloWorld Server! :)");
- get("/*", (request, response) -> {
- String url = request.splat()[0];//take the first splat param value
- return "Requested url : " + url;
- });
It prints:
- Requested url : https:/finance.yahoo.com/q/ks
The first thing is that it has removed the query string.
On top of that https:/finance.yahoo.com/q/ks
is not a valid url.
See https://github.com/perwendel/spark/issues/304#issuecomment-114055123 and https://github.com/perwendel/spark/issues/304#issuecomment-114793493
To solve this:
We can simply do some manipulate on the urls ourselves:
Corrected codes:
- get("/*", (request, response) -> {
- String url = request.splat()[0];//take the first splat param value
- url = manipulateUrl(url, request.queryString());
- return "Requested url : " + url;
- });
- //let's modify url param
- public static String manipulateUrl(String urlStr, String queryStr) throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {
- urlStr = urlStr.replaceFirst("/", "//");
- if (queryStr.length() >= 0) {
- urlStr = urlStr + "?" + queryStr;
- }
- return urlStr;
- }
No comments:
Post a Comment