How to concatenate API request URL safely - url

Let's imagine I have the following parts of a URL:
val url_start = "http://example.com"
val url_part_1 = "&fields[...]&" //This part of url can be in the middle of url or in the end
val url_part_2 = "&include..."
And then I try to concatenate the resulting URL like this:
val complete_url = url_start + url_part_2 + url_part_1
In this case I'd get http://example.com&include...&fields[...]& (don't consider syntax here), which is one & symbol between URL parts which means that concatenation was successful, BUT if I use different concat sequence in a different request like this:
val complete_url = url_start + url_part_1 + url_part_2
I'd get http://example.com&fields[...]&&include..., to be specific && in this case. Is there a way to ensure that concatenation is safer?

To keep you code clean use an array or object to keep your params and doin't keep "?" or "&" as part of urlStart or params. Add these at the end. e.g.
var urlStart = "http://example.com"
var params=[]
params.push ('a=1')
params.push ('b=2')
params.push ('c=3', 'd=4')
url = urlStart + '?' + params.join('&')
console.log (url) // http://example.com?a=1&b=2&c=3&d=4

First, you should note that it is invalid to have query parameters just after domain name; it should be something like http://example.com/?include...&fields[...] (note the /? part, you can replace it with / to make it a path parameter, but it's not likely that the router of the website supports parameters like this). Refer, for example, to this article: https://www.talisman.org/~erlkonig/misc/lunatech%5Ewhat-every-webdev-must-know-about-url-encoding/ to know more about what URLs can be valid.
For the simple abstract approach, you can use Kotlin's joinToString():
val query_part = arrayOf(
"fields[...]",
"include..."
).joinToString("&")
val whole_url = "http://example.com/?" + query_part
print(whole_url) // http://example.com/?fields[...]&include...
This approach is abstract because you can use joinToString() not only for URLs, but for whatever strings you want. This also means that if there will be an & symbol in one of the input strings itself, it will become two parameters in the output string. This is not a problem when you, as a programmer, know what strings will be joined, but if these strings are provided by user, it can become a problem.
For URL-aware approach, you can use URIBuilder from Apache HttpComponents library, but you'll need to import this library first.

Related

How can I do about " and ' for saved object in server side and use it for JSON.parse() in javascript?

How can I do about " and ' for saving object and use it for JSON.parse() in javascript?
Because I have some strings and user can type using " and ' in a single string, for example "some description like "abc" for '3 feet" or "about 3'5 feet" or "wel"come"". When I want to transform into a JSON, especially when I want to parse in view side, for example:
var test = '${test as JSON}';
It breaks because contains escape like \"
However, if only contains " and use this JSON.parse("[{"abc": "asda"das"}]"), still invalid, because need escape.
So, I really don't know what I should do in thoses cases. I need some explanation how to fix, avoid or magic.
JSON can be treated directly as Object in Javascript. So you can simply write:
var test = ${(test as JSON).toString()}
Optionally, you can pass true to the toString() method to make the JSON pretty string or Object.
var test = ${(test as JSON).toString(true)}

How to get rid of the starting slash in URI or URL?

I am using
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
String path2 = path.substring(1);
because the output of the method getPath() returns sth like this:
/C:/Users/......
and I need this
C:/Users....
I really need the below address because some external library refuses to work with the slash at the beginning or with file:/ at the beginning or anything else.
I tried pretty much all the methods in URL like toString() toExternalPath() etc. and done the same with URI and none of it returns it like I need it. (I totally don't understand, why it keeps the slash at the beginning).
It is okay to do it on my machine with just erasing the first char. But a friend tried to run it on linux and since the addresses are different there, it does not work...
What should with such problem?
Convert the URL to a URI and use that in the File constructor:
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
File file = new File(res.toURI());
String fileName = file.getPath();
As long as UNIX paths are not supposed to contain drive letters, you may try this:
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
char a_char = text.charAt(2);
if (a_char==':') path = path.substring(1);
Convert to a URI, then use Paths.get().
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = Paths.get(res.toURI()).toString();
You could probably just format the string once you get it.
something like this:
path2= path2[1:];
I was searching for one-line solution, so the best what i came up with was deleting it manually like this:
String url = this.getClass().getClassLoader().getResource(dictionaryPath).getPath().replaceFirst("/","");
In case if someone also needs to have it on different OS, you can make IF statement with
System.getProperty("os.name");

How do I add a query parameter to a URL?

What's the best practice for adding a query parameter to a URL in Tritium (Moovweb SDK)? Looking for something that works where you don't know if the URL has a "?" and other query parameters already.
Here's a short snippet of Tritium that should help you out in your Moovweb project. Just replace the "query_param=true" bit with the query parameter you want to add.
It selects the href of every a tag, then looks for any existing query parameters (by looking for a "?" in the href). If there are some existing, it just appends the new query parameter. If there are no existing query parameters on the href, it uses the ? to add one to the URL.
$q = "query_param=true"
$("//a[#href]") {
%s = fetch("./#href")
match(%s) {
with(/\?/) {
attribute("href", %s + "&" + $q)
}
else() {
attribute("href", %s + "?" + $q)
}
}
log(%s)
}
(You could also turn that into a function if you wanted!)
I think there is going to be a new URL scope soon so you'll be able to do things like this much more easily!

Removing a part of a URL with Ruby

Removing the query string from a URL in Ruby could be done like this:
url.split('?')[0]
Where url is the complete URL including the query string (e.g. url = http://www.domain.extension/folder?schnoo=schnok&foo=bar).
Is there a faster way to do this, i.e. without using split, but rather using Rails?
edit: The goal is to redirect from http://www.domain.extension/folder?schnoo=schnok&foo=bar to http://www.domain.extension/folder.
EDIT: I used:
url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
parsed_url = URI.parse(url)
new_url = parsed_url.scheme+"://"+parsed_url.host+parsed_url.path
Easier to read and harder to screw up if you parse and set fragment & query to nil instead of rebuilding the URL.
parsed = URI::parse("http://www.domain.extension/folder?schnoo=schnok&foo=bar#frag")
parsed.fragment = parsed.query = nil
parsed.to_s
# => "http://www.domain.extension/folder"
url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
u = URI.parse(url)
p = CGI.parse(u.query)
# p is now {"schnoo"=>["schnok"], "foo"=>["bar"]}
Take a look on the : how to get query string from passed url in ruby on rails
You can gain performance using Regex
'http://www.domain.extension/folder?schnoo=schnok&foo=bar'[/[^\?]+/]
#=> "http://www.domain.extension/folder"
Probably no need to split the url. When you visit this link, you are pass two parameters to back-end:
http://www.domain.extension/folder?schnoo=schnok&foo=bar
params[:schnoo]=schnok
params[:foo]=bar
Try to monitor your log and you will see them, then you can use them in controller directly.

URL manipulation: http://example.com/foo.jpg -> http://example.com/foo.preview.png

In rails I want to wrote some code to change this url string
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg
to
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.png
Should I use regular Expression to change it?
I'm new to Regexp, anyone can show me how to do this, and how to learn this stuff
thanks
If the extension is of fixed length, you're better off using string slicing.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
print url[0..-5] + ".preview" + url[-4..-1]
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpg
Or if your extensions are of variable length you can use rindex() to find the start of the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
dot_index = url.rindex(".")-1
print url[0..dot_index] + ".preview" + url[dot_index+1..-1]
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
If you must use a regex then do it like this:
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
print url.gsub(/\.(\w{2,4})$/, ".preview.\\1")
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
If you're sure the file ends with .jpg, you can to
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
url.gsub(".jpg", ".preview.jpg")
Otherwise, you can get the filename, then append the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
ext = File.extname(url)
url.gsub(ext, ".preview{ext}")
A string replace seems to be enough.
".jpg" -> ".preview.png"
Unfortunately I do not know ruby.
In python it'll be
new_url = url.replace(".jpg",".preview.png",1)
I think that it'll be similar in ruby. It seems to be sub() instead.
new_url = url.sub(".jpg",".preview.png")

Resources