API REST Android Backslash in URI - java

I want to use this API REST method
http://datos.santander.es/api/rest/datasets/control_flotas_estimaciones.json?query=ayto\:paradaId:454&data=ayto:paradaId,ayto:etiqLinea,ayto:tiempo1,ayto:destino1
If you see the URL, there is a param "ayto\:paradaId:454" that uses a backslash
When i try to use it in Android, I get a IllegalFormatException because of the backslash
HttpGet get = new
HttpGet("http://datos.santander.es/api/rest/datasets/control_flotas_estimaciones.json?query=ayto\:paradaId:454&data=ayto:paradaId,ayto:etiqLinea,ayto:tiempo1,ayto:destino1");
Is there any way that i can use this URL? Alternatives?
Thanks a lot!
EDIT:
I also tried to put "ayto\\:paradaId" with two backslash and i got the same exception when I get the URI...

You have to escape the backslash:
"...query=ayto\\:paradaId..."
^^
To prove that this is only one character, you can check
"\\".length()

Related

Passing two forward slashes as path param in Rest API

#Path("/{code:.+}")
public Response getTemplateForCode(#PathParam("code") String code)
I want to pass URI in path parameter eg(ABC://HELLO). But iam getting only single slash ABC:/HELLO only. Can anyone tell how to get double slashes with full uri ABC://HELLO. Is there any REGEX to get double slashes?
I don't want to pass in query params
In Java regex we can use a backslash to escape the special meaning of a slash.
The pattern
\w+:\/\/\w+
matches
ABC://HELLO
See https://regex101.com/r/5vRHHN/1

How to replace double slash with single slash for an url

For the given url like "http://google.com//view/All/builds", i want to replace the double slash with single slash. For example the above url should display as "http://google.com/view/All/builds"
I dint know regular expressions. Can any one help me, how can i achieve this using regular expressions.
To avoid replacing the first // in http:// use the following regex :
String to = from.replaceAll("(?<!http:)//", "/");
PS: if you want to handle https use (?<!(http:|https:))// instead.
Is Regex the right approach?
In case you wanted this solution as part of an exercise to improve your regex skills, then fine. But what is it that you're really trying to achieve? You're probably trying to normalize a URL. Replacing // with / is one aspect of normalizing a URL. But what about other aspects, like removing redundant ./ and collapsing ../ with their parent directories? What about different protocols? What about ///? What about the // at the start? What about /// at the start in case of file:///?
If you want to write a generic, reusable piece of code, using a regular expression is probably not the best appraoch. And it's reinventing the wheel. Instead, consider java.net.URI.normalize().
java.net.URI.normalize()
java.lang.String
String inputUrl = "http://localhost:1234//foo//bar//buzz";
String normalizedUrl = new URI(inputUrl).normalize().toString();
java.net.URL
URL inputUrl = new URL("http://localhost:1234//foo//bar//buzz");
URL normalizedUrl = inputUrl.toURI().normalize().toURL();
java.net.URI
URI inputUri = new URI("http://localhost:1234//foo//bar//buzz");
URI normalizedUri = inputUri.normalize();
Regex
In case you do want to use a regular expression, think of all possibilities. What if, in future, this should also process other protocols, like https, file, ftp, fish, and so on? So, think again, and probably use URI.normalize(). But if you insist on a regular expression, maybe use this one:
String noramlizedUri = uri.replaceAll("(?<!\\w+:/?)//+", "/");
Compared to other solutions, this works with all URLs that look similar to HTTP URLs just with different protocols instead of http, like https, file, ftp and so on, and it will keep the triple-slash /// in case of file:///. But, unlike java.net.URI.normalize(), this does not remove redundant ./, it does not collapse ../ with their parent directories, it does not other aspects of URL normalization that you and I might have forgotten about, and it will not be updated automatically with newer RFCs about URLs, URIs, and such.
String to = from.replaceAll("(?<!(http:|https:))[//]+", "/");
will match two or more slashes.
Here is the regexp:
/(?<=[^:\s])(\/+\/)/g
It finds multiple slashes in url preserving ones after protocol regardless of it.
Handles also protocol relative urls which start from //.
#Test
public void shouldReplaceMultipleSlashes() {
assertEquals("http://google.com/?q=hi", replaceMultipleSlashes("http://google.com///?q=hi"));
assertEquals("https://google.com/?q=hi", replaceMultipleSlashes("https:////google.com//?q=hi"));
assertEquals("//somecdn.com/foo/", replaceMultipleSlashes("//somecdn.com/foo///"));
}
private static String replaceMultipleSlashes(String url) {
return url.replaceAll("(?<=[^:\\s])(\\/+\\/)", "/");
}
Literally means:
(\/+\/) - find group: /+ one or more slashes followed by / slash
(?<=[^:\s]) - which follows the group (*posiive lookbehind) of this (*negated set) [^:\s] that excludes : colon and \s whitespace
g - global search flag
I suggest you simply use String.replace which documentation is http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(java.lang.CharSequence, java.lang.CharSequence)
Something like
`myString.replace("//", "/");
If you want to remove the first occurence:
String[] parts = str.split("//", 2);
str = parts[0] + "//" + parts[1].replaceAll("//", "/");
Which is the simplest way (without regular expression). I don't know the regular expression corresponding, if there is an expert looking at the thread.... ;)

Java Regex not working?

I am trying to send the following parameters to a server through HTTP POST:
["my_session_id","{this=that, foo=bar}"]
But the server is returning a parse error because of the quotes around the hash.
I am trying to remove them with a regex like so:
params.replaceAll("\\\"\\{", "\\{");
params.replaceAll("\\\"\\}", "\\}");
In all honestly I have no idea what I'm doing. Please help.
Thanks in advance!
There's two issues here: First, you're not re-assigning the string. Strings are immutable in Java (cannot be changed), so you must assign the result. Second, you're replacing "} instead of }".
Here's what I used:
String params = "[\"my_session_id\",\"{this=that, foo=bar}\"]";
params = params.replaceAll("\\\"\\{", "\\{");
params = params.replaceAll("\\}\\\"", "\\}");
System.out.println(params);
Which prints out:
["my_session_id",{this=that, foo=bar}]
PS: Bit of advice, use JSON. Android has excellent JSON handling, and it is supported in PHP as well.
Is there a reason you are using the regular expression replaceAll? Alternatively, you might try:
String parameters = parameters.replace("{", "\\{").replace("}", "\\}");

how to replace brackets in url with bracket encoding?

I need a regex pattern that will find and replace brackets in urls to its urls encoding.
For example a base url like:
http://www.mysite.com/bla/blabla/abc[1].txt
will be turned to:
http://www.mysite.com/bla/blabla/abc%5B1%5D.txt
can anyone help please?
EDIT1:
i originaly use commons-httpclient to access this kind of urls.
when I use the first URL I get an "escaped absolute path no valid" exception.
I can't use URLENCODER because when I use it, I get a "host parameter is null" exception.
The following line should do the trick
String s = URLEncoder.encode("http://www.mysite.com/bla/blabla/abc[1].txt", "UTF-8");
Have you tried URLEncoder.encode?
in the java.net.URLEncoder package.
EDIT:
Ok i see... you cannot pass an entire URL to URLEncoder. URLEncoder is mostly used to encode query parameters.
try this instead:
URI uri = new URI("http", "www.mysite.com", "/bla/blabla/abc[1].txt",null);
System.out.println(uri.toASCIIString());

Search and replace "/" at end of url's using regular expressions in java

Below is my regular expression :-
\\bhttps?://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]\\b
when the request url is of type http://www.example.com/ , the last character is not replaced in my shortner url and / is appended at end.
The regex is not able to find the last /.
Please help with this.
I think that / would be a word boundary, so maybe it works better if you add a ? to the and, so it reads:
\\bhttps?://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]\\b?
what about:
if(url.endsWith("/"))
url = url.substring(0,url.length()-1);
or if you need to use regular expressions you can do something like this:
url = url.replaceAll("(\\bhttps?://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*)/(\\b?)","$1$2");
If all you want is to replace the trailing / (which is what your question directly asks), you can simply do:
url = url.substring(0, url.lastIndexOf('/'));
Remember to KISS often.
You could simply use:
url = url.replaceAll("\/+$","");

Categories