使用Java创建URL-最佳实践是什么?

时间:2018-06-22 14:05:20

标签: java url

我有一个调用休息服务的应用程序。我需要给它传递一个URL,现在我要通过串联一个字符串来创建URL。

我正在这样做:

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

以上显然是假的,但重点是我使用的是简单的字符串concats。

这是最佳做法吗?我对Java比较陌生。我应该改为构建URL对象吗?

谢谢

4 个答案:

答案 0 :(得分:0)

如果使用的是jersey-client。以下是在不使代码变得丑陋的情况下访问子资源的最佳实践。

资源:/ 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();

答案 1 :(得分:0)

如果您的基本路径需要添加一些其他字符串,则有两个选项:

首先是使用String.format()

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

或使用String.replace()

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

关于这两个答案的好处是,不需要插入的字符串不必在末尾。

答案 2 :(得分:0)

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

它具有各种构造函数,您可以阅读here

示例

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

答案 3 :(得分:0)

请勿使用String操作来生成REST url,因为它很尴尬。考虑一种情况,您需要将一组查询参数添加到您的URL。使用String串联会产生多大的错误。相反,有内置库可以满足此目的。一个这样的库是apache httpclient。 Spring提供了另一个变体。这是使用apache httpclient的示例。

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

URIBuilder builder = new URIBuilder("http://api/controller");
builder.addParameter("one", "two");
System.out.println(builder.build().toString());

这里是使用Spring org.springframework.web.util.UriComponentsBuilder

的相同实现
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://api/controller");
builder.path("/newPath");
builder.queryParam("one", "1");
System.out.println(builder.build().toUriString());

这是Oracle documentation

相关问题