1

I have an application that is calling a rest service. I need to pass it a URL and right now I'm creating the URL by concatenating a string.

I'm doing it this way:

String urlBase = "http:/api/controller/";  
String apiMethod = "buy";
String url = urlBase + apiMethod;

The above is fake obviously, but the point is I'm using simple string concats.

Is this the best practice? I'm relatively new to Java. Should I be building a URL object instead?

Thanks

KSS
  • 821
  • 3
  • 10
  • 26

3 Answers3

1

if you have a base path which needs some additional string to be added to it you have 2 options:

First is, using String.format():

String baseUrl = "http:/api/controller/%s"; // note the %s at the end
String apiMethod = "buy";
String url = String.format(baseUrl, apiMethod);

Or using String.replace():

String baseUrl = "http:/api/controller/{apiMethod}";
String apiMethod = "buy";
String url = baseUrl.replace("\\{apiMethod}", apiMethod);

The nice thing about both answers is, that the string that needs to be inserted, doesn't have to be at the end.

Lino
  • 19,604
  • 6
  • 47
  • 65
0

If you are using jersey-client. The following would be the best practice to access the subresources without making the code ugly

Resource: /someApp

Sub-Resource: /someApp/getData

    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.target("https://localhost:7777/someApp/").path("getData");
    Response response = webTarget.request().header("key", "value").get();
Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19
0

If you are using plain Java, it's better to use dedicated class for URL building which throws exception if provided data are invalid in semantic way.

It has various constructors, you can read about it here.

Example

URL url = new URL(
   "http",
   "stackoverflow.com",
   "/questions/50989746/creating-a-url-using-java-whats-the-best-practive"
);
System.out.println(url);
Peteef
  • 377
  • 1
  • 2
  • 10