Question: Java Parse a url and extract the GET arguments http:// localhost :1234 /path ? key=value type host name port resource path arguments You cannot use

Java

Parse a url and extract the GET arguments

http:// localhost :1234 /path ? key=value

type host name port resource path arguments

You cannot use URL class to solve this, it has to be parsed the manual way

//////////////////////////////////////////////////////////////////////////////////////////////////

[ParsedUrl File]

package parser; import java.util.HashMap; import java.util.Map; public class ParsedUrl { final String path ; public ParsedUrl(String url){ } public String getValue(String key){ return null; } public boolean hasQueryArgs(){ return false; } public String getPath() { return null; } }

////////////////////////////////////////////////////////////////////////////////////////////////

[ParserTest File]

package parser; import org.testng.Assert; import org.testng.annotations.Test; public class ParserTests { @Test public void doTest(){ String random = String.valueOf(Math.random()); String random2 = String.valueOf(Math.random()); String randomKey = String.valueOf(Math.random()); String randomKey2 = String.valueOf(Math.random()); ParsedUrl parsedUrl; // this is a sample assert Assert.assertEquals(true, true); parsedUrl = new ParsedUrl("http://localhost:1234/"); Assert.assertEquals(parsedUrl.path, "/"); Assert.assertFalse(parsedUrl.hasQueryArgs()); parsedUrl = new ParsedUrl("http://localhost:1234/endpoint1"); Assert.assertEquals(parsedUrl.path, "/endpoint1"); Assert.assertFalse(parsedUrl.hasQueryArgs()); parsedUrl = new ParsedUrl("http://www.mysite.com:1234/endpoint1?" + randomKey + "=" + random); Assert.assertEquals(parsedUrl.path, "/endpoint1"); Assert.assertEquals(parsedUrl.getValue(randomKey), random); Assert.assertNull(parsedUrl.getValue(random2)); parsedUrl = new ParsedUrl("https://localhost:5555/endpoint1/anotherpath?" + randomKey2 + "=" + random); Assert.assertEquals(parsedUrl.path, "/endpoint1/anotherpath"); Assert.assertEquals(parsedUrl.getValue(randomKey2), random); Assert.assertNull(parsedUrl.getValue(random2)); } } 

////////////////////////////////////////////////////////////////////////////////////////////////////////////

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!