How to make Get Request with Request param in Postman - spring-boot

I have created an endpoint that accepts a string in its request param
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression") String expression) {
System.out.println(expression);
// code to validate the input string
}
While sending the request from postman as
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606/Curr_month:Y07608
// lets say this is a valid input
console displays as
Y07607=Curr_month:Y07606/Curr_month:Y07608 Valid
But when i send
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606+Curr_month:Y07608
//which is also an valid input
console displays as
Y07607=Curr_month:Y07606 Curr_month:Y07608 Invalid
I am not understanding why "+" is not accepted as parameter.
"+" just vanishes till it reaches the api! Why?

I suggest to add this regular expression to your code to handle '+' char :
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression:.+") String expression) {
System.out.println(expression);
// code to validate the input string
}

I didn't find any solution but the reason is because + is a special character in a URL escape for spaces. Thats why it is replacing + with a " " i.e. a space.
So apparently I have to encode it from my front-end

Its wise to encode special characters in a URL. Characters like \ or :, etc.
For + the format or value is %2. You can read more about URL encoding here. This is actually the preferred method because these special characters can sometimes cause unintended events to occur, like / or = which can mean something else in the URL.
And you need not worry about manually decoding it in the backend or server because it is automatically decoded, in most cases and frameworks. In your case, I assume you are using Spring Boot, so you don't need to worry about decoding.

Related

How to limit the number of characters in laravel to convert to URL

I am using the google geocoding API to get latitude and longitude of addresses, the problem is that it is for Japanese users, which have "special" characters and when I use the service, the URL is too long
that results in a ZERO_RESULTS response
{
"results" : [],
"status" : "ZERO_RESULTS"
}
instead, if I delete some characters, I do get the results I want, what I'm looking for is to achieve that, for example
$customerAddress = "日本 〒462-0825 愛知県 名古屋市北区 大曽根3丁目 13-2V-Handsビル 1F"
do not exceed the number of characters allowed by the URL, which in the end I end up putting together like this
$geocodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=$customerAddress&key=$apiKey";
it doesn't matter if i remove characters from the end, but I need the address to not be SO specific so it can fit in the url
with this tool, we can verify what I say when placing the example address, we receive ZERO_RESULTS until we delete part of the text
how could I do it?
here is more documentation of the construction of the URL
URL encode to verify that it is too long by placing Japanese characters
You can use the Laravel Str helper to limit your string like this:
use Illuminate\Support\Str;
$rawCustomerAddress = "a very long address";
$maxAddressLength = 200;
$customerAddress = Str::limit($rawCustomerAddress, $maxAddressLength);
$geocodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=$customerAddress&key=$apiKey";
More details in the documentation

Search Query Parameter

I want to search email which contains '+' in it. for example
something like this myemail.subdomain+1#domain.com.
URL - https://example.com?searchKey=myemail.subdomain+1#
I am using Laravel, this parameter is fetched from route using
$request->get('searchKey');
but it's converting '+' to ' ' ,
as a result i am getting
searchKey as myemail.subdomain 1#
which leads to improper result.
Any help?
PHP assumes that + from GET request is a space. Right encoded plus symbol is %2B.
You have to just prepare string from request to save plus symbol:
$searchKey= urlencode(request()->get('searchKey'));
In your case you'll get # as %40. Then you can replace plus with correct code and decode it. But then be careful with usual spaces!
$searchKey = urlencode(request()->get('searchKey'));
$searchKey = urldecode(str_replace('+', '%2B', $searchKey));
https://www.php.net/manual/en/function.urlencode.php
https://www.php.net/manual/en/function.urldecode.php
P.S. I suppose it is not the best soulution, but it should work.
P.P.S. Or, if you can prepare plus as a %2B before it will be at search parameter, do it

Validation fails when passing a file path as Input Argument to Orchestrator API StartJobs

I am trying to use file name path (Ex: C:\Document\Report.txt) as a parameter through uipath orchastrator api. I tried different approach and In each approach I am getting Bad request error "{"message":"Argument Values validation failed.","errorCode":2003,"resourceIds":null}"
Below is my Example code
FileListUploaded ="C\\Documents\\report.txt";
string parameter1 = "{\"startInfo\": {\"ReleaseKey\": \"xxxxx-xxx-xxx-xxx-xxxxxx\"," +
"\"RobotIds\": [xxxxx]," +
"\"JobsCount\": 0," +
"\"InputArguments\": \"{ "+
"\\\"reports_or_other_files\\\": \\\" + FileListUploaded + \\\"}\"}}";
request_startRobot.AddParameter("application/json; charset=utf-16", parameter, ParameterType.RequestBody);
IRestResponse response_startRobot = client_startRobot.Execute(request_startRobot);
That's a bit messy to look at, but it appears you are not quoting and escaping your JSON correctly.
I might suggest building an array and serializing it into JSON to make it easier to read, or using a HEREDOC or string formatting. If you do continue to concatenate your JSON body string together, dump out the results to see how it is coming together.
The final results of the JSON should look something like
{
"startInfo": {
"ReleaseKey":"{{uipath_releaseKey}}",
"Strategy":"JobsCount",
"JobsCount":1,
"InputArguments":"{\"reports_or_other_files\":\"C:\\\\Documents\\\\report.txt\"}"
}
}
With the InputArguments:
Looks like you are missing some quotes
Might need to double escape your backslashes in the FileListUploaded variable
Missing a colon after the C in the path

How to return localized content from WebAPI? Strings work but not numbers

Given this ApiController:
public string TestString() {
return "The value is: " + 1.23;
}
public double TestDouble() {
return 1.23;
}
With the browser's language set to "fr-FR", the following happens:
/apiController/TestString yields
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">The value is: 1,23</string>
/apiController/TestDouble yields
<double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1.23</double>
I would expect TestDouble() to yield 1,23 in the XML. Can anyone explain why this isn't the case and, more importantly, how to make it so that it does?
It is because the conversion from double to string happens at different stage for each API. For the TestString API, double.ToString() is used to convert the number to a string using CurrentCulture of the current thread and it happens when the TestString method is called. Meanwhile, the double number which is returned by TestDouble is serialized to string during the serialization step which uses GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Culture.
In my opinion, both should use InvariantCulture. On the consumer side, the values will be parsed and be formatted with the correct culture.
Update: this is only used for JsonFormatter. XmlFormatter doesn't have such a setting.
Update 2:
It seems (decimal) numbers need special converter to make it culture-aware:
Handling decimal values in Newtonsoft.Json
Btw, if you want o change data format per action/request, you can try the last piece of code of the following link: http://tostring.it/2012/07/18/customize-json-result-in-web-api/

Passing a filepath over url

I need to pass this filepath over via route to my actionmethod:
<p>#car.Name</p>
so for example #car.ContainerPath is a string of "34_Creating%20Cars%20Forms/Exercise%20Cars/Audi%202010%20Parts%20Reference.pdf"
I need to escape this somehow I think? I would prefer not to send this over url but with a hyperlink I don't see a way not to.
UPDATE:
For additional info, here's the actionmethod it's going to:
public string GetFileZipDownloadUrl(CarViewModel model, string fileContainerPath)
{
string downloadUrl = string.Empty;
downloadUrl = GetFileZipDownloadUrl(model.CarId,fileContainerPath, model.UserId);
return downloadUrl;
}
so I'm sending over for that fileContainerPath paths like this in the url for that #car.ContainerPath param:
"55_Creating Cars Forms/Exercise Cars/Audi Parts Reference.pdf"
so the route url before it's requested looks like this when formed in that hyperlink:
http://Cars/55/55_Creating Cars Forms/Exercise Cars/Audi Parts Reference.pdf/20/Url
My action method just needs to use that path to go get a reference to a file under the hood.
If you want to just get rid of %20 in the url use encoding/decoding like in #Xander's answer. However if any of your data is very dynamic and can have weird characters you should consider adding a Safe() and Unsafe() methods that will strip out all the "Dangerous" characters for url, and then turn it back to original value.
Raw Url:
HttpUtility.UrlEncode(rawurl);
Decode encoded url:
HttpUtility.UrlDecode(encodedurl);
http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx

Resources