This is the standard form using URL in java
URL(URL baseURL, String relativeURL)
String baseURL= "http://www.site.com/";
Form the relativeURL using the StringBuilder or String based on your parameters.
Other way is to go for Third Party LIB.
题
I have been working with java.net.URL class and I'm at the point where I need to add parameters to the URL object variable. I have seen many ways to add parameters such as string concatenation or creating new URL objects and passing the wanted parameters to the URL class constructor. But I have also seen UriBuilder and other ways to create URLs or URIs and later add parameters to them. What is the proper way to construct a URL in java to later add parameters?
The lazy way I've been doing it is as follow:
String url = "http://www.site.com/";
url += "?";
url += "param1=" + 1;
url += "&";
url += "param2=" + 2;
URL url = new URL(url);
Is that the best way to add parameters to an URL? is there a better way?
Thanks, Y_Y
解决方案
This is the standard form using URL in java
URL(URL baseURL, String relativeURL)
String baseURL= "http://www.site.com/";
Form the relativeURL using the StringBuilder or String based on your parameters.
Other way is to go for Third Party LIB.
其他提示
If your don't have any restrictions on using an external library, I suggest adding Apache HttpClient
Below is an example:
URIBuilder builder = new URIBuilder("http://google.com/search");
builder.addParameter("q","web apps");
System.out.println(builder.build().toString()); //outputs http://google.com/search?q=web+apps