How add a trailing slash after the port in apache URIBuilder?

1.2k views Asked by At

I am trying to build a URI having a trailing slash but can't happen to find the way to do it with URIBuilder. Is that even possible?

Expected result would be: http://test.com:24/?param1=value1&param2=value2

@Test
public void ttt(){
    final URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http");
    uriBuilder.setHost("test.com");
    uriBuilder.setPort(24);
    uriBuilder.addParameter("param1", "value1");
    uriBuilder.addParameter("param2", "value2");
    System.out.println(uriBuilder.toString());
}

What I get at the moment: http://test.com:24?param1=value1&param2=value2

Any idea?

2

There are 2 answers

0
rkosegi On BEST ANSWER

There is setPath(str) method, see URIBuilder.setPath(String)

So your code should look like

@Test
public void ttt(){
    final URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http");
    uriBuilder.setHost("test.com");
    uriBuilder.setPort(24);
    uriBuilder.setPath("/");
    uriBuilder.addParameter("param1", "value1");
    uriBuilder.addParameter("param2", "value2");
    System.out.println(uriBuilder.toString());
}

Output

http://test.com:24/?param1=value1&param2=value2
1
Raz K On

You can always add manually the slash:

int len = "http://test.com:24".length()
String newstr = uriBuilder.toString().substring(0,len) + "/" + uriBuilder.toString().substring(len);
System.out.println(newstr)

Since you know the url (you have built it manually) you can use this way to add the slash.
More general solution is to find the second ':' and add slash after the last digit of the port:

String str = uriBuilder.toString();
int ind = str.indexOf(':',6) + 1;
while(ind < str.length() && Character.isDigit(str.charAt(ind)))
    ind++;
String newstr = str.substring(0,ind) + "/" + str.substring(ind);