Error in building a URL string in java - java

I am having a hard time in building a URL string which I want to use for HttpURLConnection.
Here is the string that I want to pass
http://api.fixer.io/latest?base=USD&symbols=USD,GBP
The above string shall have all the parameter as dynamic, two Strings that I am using are part1 and other default_actv2
I tried building string in following way
http://api.fixer.io/latest?base="+part1+"&symbols="+part1+","+default_actv2
and passing it into jsonTask in following way
new JSONTask().execute("http://api.fixer.io/latest?base="+part1+"&symbols="+part1+","+default_actv2);
When I print the value my code takes it as
http://api.fixer.io/latest?base=AED &symbols=AED ,INR
Notice the extra spaces after AED, as a result of such a string. I am getting error from the server side.
Could anybody help in explaining me the correct way of building a string with some code. I know there are tons of threads that answers this question, but somehow I am not able to get this thing working.
Thanks In advance

You can use .trim() on your part1 string in order to deal with the extra space.

You can use Apache URIBuilder.
URI uri = new URIBuilder()
.setScheme("http")
.setHost("api.fixer.io")
.setPath("/latest")
.addParameter("base", part1)
.addParameter("symbol", part1 + "," + default_actv2)
.build();
uri.toString();

Related

How to replace characters at PathVariable in SpringBoot

I tried a couple of solutions but was unable to solve it. I looking for a solution where I can replace special characters in Path Variable in Spring Boot.
Example
xyz.com/3233+23+232+323
I am looking for a possible solution where Spring #PathVariable returns me the String "323323232323" without + sign.
I know I can do a simple String replace, but there are 100's of API's and it will be difficult to do that.
I am looking for something with minimal changes required.
One way, just read the #PathVariable value, then apply a regular expression.
Just One line, Example:
#GetMapping("/read/{str}")
public String check(#PathVariable String str){
String modifiedStr = str.replaceAll("\\+", "");
return modifiedStr;
}
Sample: http://localhost:8080/ticket-service/read/3233+23+232+323
Output: 323323232323

Rest assured : Illegal character in path

I am using response retrieved from one endpoint as path param in another endpoint.
However, when used in URI, it throws java.net.URISyntaxException: Illegal character in path.
//Post the endpoint
Response resp2 = RestAssured.given().
pathParam("id", build).
log().all().
when().urlEncodingEnabled(false).post("https://abc/{id}");
This is because the value of id used in uri is with double quotes like :-
https://abc/"id".
How can I get rid of these double quotes so as to use the value of id in uri , please advise.
First talk to the developer about this, because the nature of path param (/{id}) is to be replaced by a legitimate value (not enclosed in quotes); something like https://abc/23 or https://abc/param
I would not suggest any work-around for this as this is implemented in a wrong way from REST end point definition. You might go ahead and raise a defect against this.
Taking a shot in the dark here because I feel like the issue could possibly be coming from how you're getting the string from that response. If you're pulling it from a JSON using GSON or similar:
String name = myResponseJsonObject.get("member_name")
System.out.Println(name);
will print
"John"
whereas
String name = myResponseJsonObject.get("member_name").getAsString()
System.out.Println(name);
will give you
John
A small detail but this has tripped me up when using GSON and others when working with JSONs in java.
Thank you John and Mohan for your time , I really appreciate it.
I resolved this issue yesterday evening using Stringof function which removed the double quotes and provided me the String like value.

How can I get value after hashtag from URL in Java

I have a URL and I want to print in my graphical user interface the ID value after the hashtag.
For example, we have www.site.com/index.php#hello and I want to print hello value on a label in my GUI.
How can I do this using Java in Netbeans?
Simple solution is getRef() in URL class:
URL url = new URL("http://www.anyhost.com/index.php#hello");
jLabel.setText(url.getRef());
EDIT: According to #Henry comment:
I would recommend to use the java.net.URI as it also deals with encoding. The Javadocs say: "Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL()."
and this comment:
Why not just doing uri.getFragment()
URI uri = new URI("http://www.anyhost.com/index.php#hello");
jLabel.setText(uri.getFragment());
Use the String.split() Method.
public static String getId(string url) {
return url.split("#")[1];
}
String.split() returns an array of Strings that are delimited, or "Split," by the value you pass to it, or in this case #.
Because you want only the string after the #, you can just use the second item in the array that it returns by adding [1] to the end of it.
For more on String.split() go to Tutorials Point.
By the way, the part of the URL you are referencing is the Element ID. It is used to jump to an Element on a webpage.

Regex to Extract First Part of URL

I need a java regex to extract parts of a URL.
For example, take the following URLs:
http://localhost:81/example
https://test.com/test
http://test.com/
I would want my regex expression to return:
http://localhost:81
https://test.com
http://test.com
I will be using this in a Java patcher.
This is what I have so far, problem is it takes the whole URLs:
^https?:\/\/(?!.*:\/\/)\S+
import Java.net.URL
//snip
URL url = new URL(urlString);
return url.getProtocol() + "://" + url.getAuthority();
The right tool for the right job.
Building off your attempt, try this:
^https?://[^/]+
I'm assuming that you want to capture everything until the first / after http://? (That's what I was getting from your examples - if not, please post some more).
Are these URLs given as one input, or are each a different string?
Edit: It was pointed out that there were unnecessary escapes, so fixed to a more condensed version
Language independent answer:
For the whitespace: replace /^\s+/ with the empty string.
For removing the path information from the URL, if you can assume there aren't any slashes in the path (i.e. you're not dealing with http://localhost:81/foo/bar/baz), replace /\/[^\/]+$/ with the empty string. If there might be more slashes, you might try something like replacing /(^\s*.*:\/\/[^\/]+)\/.*/ with $1.
A simple one: ^(https?://[^/]+)

Java: reading a string in a particular format

I am not posting any code I am struck with. I am trying this in Java:
Issue:
I have words like:
,xxxx-1223
yyyyy,xxdd-345
$,xxxxr-7
sdsdsdd-18
so what ever format I have I should be able to read the last one:
xxxx-1223
xxdd-345
xxxxr-7
sdsdsdd-18
what so may be the words, all I need to to get the words as shown.
Use String#lastIndexOf(int) to find where the last comma occurs, and use String#substring(int) to get the rest of the string that follows.
String input = /* whatever */;
int lastComma = input.lastIndexOf(',');
String output = input.substring(lastComma + 1);
String[] str=yourWord.split(",");
String output=str[str.length-1];
You can use this Regex: -
(\\w+-\\d+)$
Or this specific problem can simply be solved using String.split() or String.substring(int) methods

Categories

Resources