I have a URL but i need only the value of http_token
i.e., somedata
in that URL so that i can send the token value as argument in my code. How do i get it?
URL:
https://website.com/?HTTP_TARGETPORTAL=7&HTTP_TOKEN=somedata&HSID_DOMAIN_URL=...
I have a URL but i need only the value of http_token
i.e., somedata
in that URL so that i can send the token value as argument in my code. How do i get it?
URL:
https://website.com/?HTTP_TARGETPORTAL=7&HTTP_TOKEN=somedata&HSID_DOMAIN_URL=...
You can pass your string to URL
and get the query parameters.
Here is a working solution motivated from answer: Parse a URI String into Name-Value Collection
public static void main(String[] args) {
String givenUrl = "https://healthsafeid-stage1.optum.com/protected/accountreset/password?HTTP_TARGETPORTAL=LAWW&HTTP_TARGETURL=https%3A%2F%2Fsr-smsc-stg.liveandworkwell.com%2Fservices%2Fsecure%2Fgn&HTTP_ERRORURL=https%3A%2F%2Fsr-smsc-stg.liveandworkwell.com%2Fcontent%2Fen%2Fpublic%2Ferror.html&HTTP_ACCESSTYPE=TIER1&HTTP_BRANDURL=&HTTP_LANGUAGE=en&HTTP_ACCESSCODE=12345678&HTTP_GRADIENTCOLOR1=&HTTP_GRADIENTCOLOR2=&HTTP_TOKEN=GthzXwVHL2xyAdMsHukFPGrSrP6GJHItc%2BEucuznsQk0%2FEhFrjTfr6r0fL16SKOQvus7y5dHmZ1LP3jUJtvY2w%3D%3D&HSID_DOMAIN_URL=https%3A%2F%2Fhealthsafeid-stage1.optum.com";
try {
URL url = new URL(givenUrl);
Map<String, String> query_pairs = new HashMap<>();
String query = url.getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8").toUpperCase(), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
String httpToken = query_pairs.get("HTTP_TOKEN");
System.out.println("Http token: " + httpToken);
} catch (MalformedURLException | UnsupportedEncodingException e) {
// log and handle the exception
}
}
Output:
Http token: GthzXwVHL2xyAdMsHukFPGrSrP6GJHItc%2BEucuznsQk0%2FEhFrjTfr6r0fL16SKOQvus7y5dHmZ1LP3jUJtvY2w%3D%3D
Advantage with this approach:
I've not worked with Java regular expressions but the whole thing should be this.
I'm not sure this will work or not. There are many ways to achieve the expected result but here is the regex way.
String line = ""; // URL HERE
String pattern = "HTTP_TOKEN=(.+)[&]*";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("HTTP TOKEN: " + m.group(1) );
}else {
System.out.println("NOT FOUND");
}
Regex Preview: https://regex101.com/r/mA8bPg/2