문제

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top