问题描述
我有一个正在调用休息服务的应用程序.我需要向它传递一个 URL,现在我正在通过连接一个字符串来创建 URL.
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.
我是这样做的:
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.
这是最佳做法吗?我对 Java 比较陌生.我应该构建一个 URL 对象吗?
Is this the best practice? I'm relatively new to Java. Should I be building a URL object instead?
谢谢
推荐答案
如果您有一个需要添加一些额外字符串的基本路径,您有两个选择:
if you have a base path which needs some additional string to be added to it you have 2 options:
首先是使用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);
这两个答案的好处是,需要插入的字符串不必在末尾.
The nice thing about both answers is, that the string that needs to be inserted, doesn't have to be at the end.
这篇关于使用 Java 创建 URL - 最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!