Créer une URL en java


Essayer de construire http://IP:4567/foldername/1234?abc=xyz. Je ne sais pas grand-chose à ce sujet, mais j'ai écrit ci-dessous le code de la recherche à partir de Google:

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class MyUrlConstruct {

    public static void main(String a[]){

        try {
            String protocol = "http";
            String host = "IP";
            int port = 4567;
            String path = "foldername/1234";
            URL url = new URL (protocol, host, port, path);
            System.out.println(url.toString()+"?");
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }
}

Je suis capable de construire l'URL http://IP:port/foldername/1234?. Je suis coincé à la partie requête. Merci de m'aider à aller de l'avant.

Author: px06, 2016-09-14

3 answers

En termes généraux non Java, une URL est un type spécialisé d'URI. Vous pouvez utiliser la classe URI (qui est plus moderne que la vénérable classe URL, qui existe depuis Java 1.0) pour créer un URI de manière plus fiable, et vous pouvez le convertir en URL avec la méthode toURL {[4] } d'URI:

String protocol = "http";
String host = "example.com";
int port = 4567;
String path = "/foldername/1234";
String auth = null;
String fragment = null;
URI uri = new URI(protocol, auth, host, port, path, query, fragment);
URL url = uri.toURL();

Notez que le path doit commencer par une barre oblique.

 6
Author: VGR, 2016-09-14 21:49:55

Vous pouvez simplement passer la spécification brute

new URL("http://IP:4567/foldername/1234?abc=xyz");

Ou vous pouvez prendre quelque chose comme org.apache.http.client.utils.URIBuilder et construisez - le de manière sûre avec un encodage URL approprié

URIBuilder builder = new URIBuilder()
builder.setScheme("http")
builder.setHost("IP")
builder.setPath("/foldername/1234")
builder.addParameter("abc", "xyz")
URL url = builder.build().toURL()
 33
Author: vsminkov, 2016-09-14 22:35:40

Utiliser OkHttp

Il existe une bibliothèque très populaire nommée OkHttpqui a été étoilée 20K fois sur GitHub. Avec cette bibliothèque, vous pouvez créer l'URL comme ci-dessous:

import okhttp3.HttpUrl;

URL url = new HttpUrl.Builder()
    .scheme("http")
    .host("example.com")
    .port(4567)
    .addPathSegments("foldername/1234")
    .addQueryParameter("abc", "xyz")
    .build().url();

Ou vous pouvez simplement analyser une URL:

URL url = HttpUrl.parse("http://example.com:4567/foldername/1234?abc=xyz").url();
 14
Author: Tyler Long, 2017-05-25 14:59:28