使用Java创建URL-What';最佳做法是什么?

使用Java创建URL-What';最佳做法是什么?,java,url,Java,Url,我有一个调用rest服务的应用程序。我需要向它传递一个URL,现在我通过连接一个字符串来创建URL 我是这样做的: String urlBase = "http:/api/controller/"; String apiMethod = "buy"; String url = urlBase + apiMethod; 上述内容显然是假的,但重点是我使用的是简单的字符串concats 这是最好的做法吗?我对Java比较陌生。我应该构建一个URL对象吗 如果您正在使用jersey客户端,请感谢

我有一个调用rest服务的应用程序。我需要向它传递一个URL,现在我通过连接一个字符串来创建URL

我是这样做的:

String urlBase = "http:/api/controller/";  
String apiMethod = "buy";
String url = urlBase + apiMethod;
上述内容显然是假的,但重点是我使用的是简单的字符串concats

这是最好的做法吗?我对Java比较陌生。我应该构建一个URL对象吗


如果您正在使用jersey客户端,请感谢。下面是访问子资源而不使代码难看的最佳实践

资源:/someApp

子资源:/someApp/getData

    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.target("https://localhost:7777/someApp/").path("getData");
    Response response = webTarget.request().header("key", "value").get();

如果基本路径需要添加一些额外的字符串,则有2个选项:

首先,使用
String.format()

或者使用
String.replace()


这两个答案的优点是,需要插入的字符串不必位于末尾。

如果您使用的是纯Java,最好使用专用类来构建URL,如果提供的数据在语义上无效,该类会引发异常

它有各种各样的构造函数,你可以阅读

示例

String baseUrl = "http:/api/controller/%s"; // note the %s at the end
String apiMethod = "buy";
String url = String.format(baseUrl, apiMethod);
String baseUrl = "http:/api/controller/{apiMethod}";
String apiMethod = "buy";
String url = baseUrl.replace("\\{apiMethod}", apiMethod);
URL url = new URL(
   "http",
   "stackoverflow.com",
   "/questions/50989746/creating-a-url-using-java-whats-the-best-practive"
);
System.out.println(url);