How to use getRequestUri().getRawQuery() in the url on Java escape - java

As know url would not allow some special character there, so need encode for that:
: metadata=[{name: serialnumber, value: aaaaaaaaa},{name: register, value: abcde}] in the url
I tried this encode would work
String abc= java.net.URLEncoder.encode("http://localhost:9080/myapp/myapp/search?metadata=[{name: serialnumber, value: aaaaaaaaa},{name: register, value: abcde}]", "utf-8");
But why would be fail following if use info.getRequestUri().getRawQuery() instead?
public Response search(#Context final UriInfo info, #Context final HttpHeaders httpHeaders) throws Exception {
String requestURI = java.net.URLEncoder.encode(info.getRequestUri().getRawQuery(), "utf-8");
error:
Caused by: java.net.URISyntaxException: Illegal character in query
How can I encode this successfully if I will use info.getRequestUri().getRawQuery()

This might be due to the white space in metadata.
You may either -
Remove the white spaces (metadata=[{name:serialnumber,value:aaaaaaaaa},{name:register,value:abcde}]
replace white spaces with +
as mentioned in this question
Hope that work!

Related

URL change encoding + instead of %20

URL encoding normally replaces a space with a plus (+) sign or with %20.
In spring MVC it replaces with %20. My controller as:
#GetMapping(path = "/post/{id}/{title}")
public String postView(#PathVariable("id") Long id, #PathVariable("title") String title, Model model){
Post post = postService.findById(id);
model.addAttribute("post", post);
return "singlePost";
}
I need to replace the %20 with (+) or (-)
Thanks
You can use decode method of URLDecoder class. As an example, if title have url encoded values,
String urlDecodedTitle = URLDecoder.decode(title, StandardCharsets.UTF_8.toString())
In the path of a URL the spaces are replaced by %20 ([RFC3986][1]), while URL query parameters follow the application/x-www-form-urlencoded that replaces spaces by +.
If you need to encode a query string parameter, you can use java.net.URLEncoder.
But as you are using #PathVariable, your parameters are part of the path, hence they must be encoded with spaces replaced by %20. Spring provides UriUtils.encodePath for this task.
For example, to build a query to your /post/{id}/{title} mapping:
Long id = 1L;
String title = "My title";
String path = "/post/" + id + "/" + UriUtils.encodePathSegment(title, "UTF-8");
On your postView method you don't need to do any decoding, as Spring does it already.
[1]: https://www.rfc-editor.org/rfc/rfc3986

Android java split string via special character fails

I would like to attach a platform parameter to a url with ? if the url has no query string and using & if url has a query string
SO i have added the following
String api_url;
//costructor next to assign apiurl value
//method to extract url and process request
processData(){
String apiUrl = "";
String[] urlParams = this.api_url.split("\\?");
if (urlParams.length > 0){
apiUrl = this.api_url+"&platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
}else {
apiUrl = this.api_url+"?platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
}
}
The above always evaluates the urlParams to a an array even when a url doesnt contain the ?
Example for a url
http://test.com
is resolved with the above code as
http://test.com&platform=12
But i expected it to be as http://test.com?platform=12
I have tried adding
String[] urlParams = this.api_url.split("?");
But it throws an error of Dangling metacharacter. What am i missing out on this. Why does this fail.
This is expected behaviour for String#split. Running "http://test.com".split("\\?") returns an array with one element, "http://test.com". So, just update your condition to if(uriParams.length > 1).
You could also consider parsing your String to a Uri, as you may not need this check and could possibly instead use:
Uri.parse(api_url)
.buildUpon()
.appendQuery("platform", tokenService.getToken(AppSettingsKeys.PLATFORM))
.build().toString();

REST Assured doesn't accept curly brackets

Unable to use query in my Endpoint URL
I have tried using .queryParams() but it does not seem to work . I am getting the following error
java.lang.IllegalArgumentException: Invalid number of path parameters.
Expected 1, was 0.Undefined path parameters are:
cycle-id[12345];test.name[Validate_REST_Assured_Curly_Brackets].
Can someone help me out
almQuery=https://{almurl}/qcbin/rest/domains/{domain}/projects/{project}/test-instances?query={cycle-id[12345];test.name[Validate_REST_Assured_Curly_Brackets]}
Response response = RestAssured.given().relaxedHTTPSValidation()
.contentType("application/xml")
.cookie(cookie) .get(getEntityEndpoint(almQuery)).then().extract().response();
This is how RestAssured implementation works. Whenever your url contains curly braces it will expect path param with for that. For example, if your url contains {project} you should provide a path param with name project.
The only way to avoid it is by manually encoding { and } characters in your url. You could use URLEncoder.encode(), but it will mess your other characters so try simply replacing all { and } with encoded values:
public class App {
public static void main(String[] args) {
String url = "http://www.example.com/path/{project}";
String encoded = encodeUrlBraces(url);
RestAssured.given()
.when()
.get(encoded);
}
private static String encodeUrlBraces(String url) {
return url.replaceAll("\\{", "%7B").replaceAll("}", "%7D");
}
}
Here's an answer for this from Rest Assured founder and contributor https://github.com/rest-assured/rest-assured/issues/682

URLEncoder - what character set to use for empty space instead of %20 or +

I am trying to open new email from my Java app:
String str=String.valueOf(email);
String body="This is body";
String subject="Hello worlds";
String newStr="mailto:"+str.trim()+"?subject="+URLEncoder.encode(subject,"UTF-8")+"&body="+URLEncoder.encode(body, "UTF-8")+"";
Desktop.getDesktop().mail(new URI(newStr));
Here it is my URLEncoding. As I cannot use body or subject string in URL without encoding them, my output here is with "+" instead of whitespace. Which is normal, I understand that. I was thinking if there is a way to visualize subject and body normally in my message? I tried with .replace("+"," ") but it is not working as it is giving an error. This is how it is now:
I think there might be different character set but I am not sure.
That's the way URLEncoder works.
One possible approach would be to replace all + with %20 after URLEncoder.enocde(...)
Or you could rely on URI constructor to encode your parameters correctly:
String scheme = "mailto";
String recipient = "recipient#snakeoil.com";
String subject = "The Meaning of Life";
String content = "..., the universe and all the rest is 42.\n Rly? Just kidding. Special characters: äöü";
String path = "";
String query = "subject=" + subject + "&body=" + content;
Desktop.getDesktop().mail(new URI(scheme, recipient, path, query, null));
Both solutions have issues:
In the first approach, you might replace actual + signs, with the second, you'll have issues with & character.

How to pass caret symbol in URL?

I need to pass ^ like a value of parameter in URL. For example:
http://localhost:8080/myapp/books?filter=^
But have an error:java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986. I've read, that I need to encode. Have something like this, but it still doesn't work. I also try to add
System.setProperty("tomcat.util.http.parser.HttpParser.requestTargetAllow" ^ ");
but for ^ it doen't help.
I have a controller:
#RequestMapping("/books")
public String getBooks(#RequestParam(value = "filter") String filter, Model model)
throws UnsupportedEncodingException {
String par = URLEncoder.encode(nameFilter,"UTF-8");
List<Books> books = (List<Books>) booksService.findAll(filter);
model.addAttribute("books", books);
return "getBooks";
}
}
Try encoding the URI before doing a request to your REST Api
For instance, when you're using JS read this:
https://www.w3schools.com/jsref/jsref_encodeURI.asp
On Java: Java URL encoding: URLEncoder vs. URI
Goodluck!
Try to follow this, it will help:
https://secure.n-able.com/webhelp/NC_9-1-0_SO_en/Content/SA_docs/API_Level_Integration/API_Integration_URLEncoding.html
#Mark’s comment is also correct.

Categories