Ajouter une URL relative à java.net.Adresse URL

pourvu que j'aie un java.net.Objet URL, pointant vers disons

http://example.com/myItems ou http://example.com/myItems/

y a-t-il un helper quelque part pour ajouter une URL relative à ceci? Par exemple, ajoutez ./myItemId ou myItemId pour obtenir : http://example.com/myItems/myItemId

27
demandé sur thSoft 2011-09-21 14:07:39

12 réponses

URL a une constructeur qui a une base de URL et un String spéc.

alternativement, java.net.URI adhère plus étroitement aux normes, et a une resolve méthode pour faire la même chose. Créer un URI à partir de votre URL en utilisant URL.toURI .

26
répondu Andrew Duffy 2011-09-21 10:15:18

celui-ci n'a pas besoin de libs ou de code supplémentaire et donne le résultat désiré:

URL url1 = new URL("http://petstore.swagger.wordnik.com/api/api-docs");
URL url2 = new URL(url1.getProtocol(), url1.getHost(), url1.getPort(), url1.getFile() + "/pet", null);
System.out.println(url1);
System.out.println(url2);

Cette affiche:

http://petstore.swagger.wordnik.com/api/api-docs
http://petstore.swagger.wordnik.com/api/api-docs/pet

la réponse acceptée ne fonctionne que s'il n'y a pas de chemin après l'hôte (IMHO la réponse acceptée est fausse)

21
répondu Christoph Henkelmann 2014-11-06 18:59:54

Voici une fonction d'aide que j'ai écrite pour ajouter au chemin de l'url:

public static URL concatenate(URL baseUrl, String extraPath) throws URISyntaxException, 
                                                                    MalformedURLException {
    URI uri = baseUrl.toURI();
    String newPath = uri.getPath() + '/' + extraPath;
    URI newUri = uri.resolve(newPath);
    return newUri.toURL();
}
5
répondu Andrew Shepherd 2014-11-07 00:36:47

j'ai cherché partout une réponse à cette question. La seule implémentation que je peux trouver est dans le SDK Android: Uri.Constructeur . J'ai extrait mes propres fins.

private String appendSegmentToPath(String path, String segment) {
  if (path == null || path.isEmpty()) {
    return "/" + segment;
  }

  if (path.charAt(path.length() - 1) == '/') {
    return path + segment;
  }

  return path + "/" + segment;
}

ce est l'endroit où j'ai trouvé la source.

en conjonction avec Apache URIBuilder , voici comment je l'utilise: builder.setPath(appendSegmentToPath(builder.getPath(), segment));

4
répondu twhitbeck 2014-05-14 16:30:44

vous pouvez utiliser URIBuilder et la méthode URI#normalize pour éviter de dupliquer / dans L'URI:

URIBuilder uriBuilder = new URIBuilder("http://example.com/test");
URI uri = uriBuilder.setPath(uriBuilder.getPath() + "/path/to/add")
          .build()
          .normalize();
// expected : http://example.com/test/path/to/add
3
répondu herau 2018-03-05 13:23:15

quelques exemples d'utilisation de L'URIBuilder Apache http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html :

Ex1:

String url = "http://example.com/test";
URIBuilder builder = new URIBuilder(url);
builder.setPath((builder.getPath() + "/example").replaceAll("//+", "/"));
System.out.println("Result 1 -> " + builder.toString());

résultat 1 - > http://example.com/test/example

Ex2:

String url = "http://example.com/test";
URIBuilder builder = new URIBuilder(url);
builder.setPath((builder.getPath() + "///example").replaceAll("//+", "/"));
System.out.println("Result 2 -> " + builder.toString());

résultat 2 - > http://example.com/test/example

1
répondu Marcelo C. 2014-05-30 17:55:55

mise à JOUR

je crois que c'est la solution la plus courte:

URL url1 = new URL("http://domain.com/contextpath");
String relativePath = "/additional/relative/path";
URL concatenatedUrl = new URL(url1.toExternalForm() + relativePath);
1
répondu Galya 2016-01-22 11:19:29

vous pouvez simplement utiliser la classe URI pour ceci:

import java.net.URI;
import org.apache.http.client.utils.URIBuilder;

URI uri = URI.create("http://example.com/basepath/");
URI uri2 = uri.resolve("./relative");
// => http://example.com/basepath/relative

notez la barre oblique sur le chemin de base et le format relatif de base du segment qui est ajouté. Vous pouvez également utiliser la classe URIBuilder du client HTTP Apache:

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

...

import java.net.URI;
import org.apache.http.client.utils.URIBuilder;

URI uri = URI.create("http://example.com/basepath");
URI uri2 = appendPath(uri, "relative");
// => http://example.com/basepath/relative

public URI appendPath(URI uri, String path) {
    URIBuilder builder = new URIBuilder(uri);
    builder.setPath(URI.create(builder.getPath() + "/").resolve("./" + path).getPath());
    return builder.build();
}
1
répondu Scott Babcock 2018-03-12 17:04:48

Concaténate un chemin relatif vers une URI:

java.net.URI uri = URI.create("https://stackoverflow.com/questions")
java.net.URI res = uri.resolve(uri.getPath + "/some/path")

res contiendra https://stackoverflow.com/questions/some/path

1
répondu Martin Tapp 2018-03-13 18:02:16

j'ai eu quelques difficultés avec L'encodage D'URI. Ajouter n'a pas fonctionné pour moi parce qu'il était d'un contenu:// type et il n'était pas aimer le "/". Cette solution ne suppose aucune interrogation, ni fragment (nous travaillons avec paths après tout):

code Kotlin:

  val newUri = Uri.parse(myUri.toString() + Uri.encode("/$relPath"))
1
répondu johnml1135 2018-06-18 19:51:25

Ma solution basée sur twhitbeck réponse:

import java.net.URI;
import java.net.URISyntaxException;

public class URIBuilder extends org.apache.http.client.utils.URIBuilder {
    public URIBuilder() {
    }

    public URIBuilder(String string) throws URISyntaxException {
        super(string);
    }

    public URIBuilder(URI uri) {
        super(uri);
    }

    public org.apache.http.client.utils.URIBuilder addPath(String subPath) {
        if (subPath == null || subPath.isEmpty() || "/".equals(subPath)) {
            return this;
        }
        return setPath(appendSegmentToPath(getPath(), subPath));
    }

    private String appendSegmentToPath(String path, String segment) {
        if (path == null || path.isEmpty()) {
            path = "/";
        }

        if (path.charAt(path.length() - 1) == '/' || segment.startsWith("/")) {
            return path + segment;
        }

        return path + "/" + segment;
    }
}

essai:

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class URIBuilderTest {

    @Test
    public void testAddPath() throws Exception {
        String url = "http://example.com/test";
        String expected = "http://example.com/test/example";

        URIBuilder builder = new URIBuilder(url);
        builder.addPath("/example");
        assertEquals(expected, builder.toString());

        builder = new URIBuilder(url);
        builder.addPath("example");
        assertEquals(expected, builder.toString());

        builder.addPath("");
        builder.addPath(null);
        assertEquals(expected, builder.toString());

        url = "http://example.com";
        expected = "http://example.com/example";

        builder = new URIBuilder(url);
        builder.addPath("/");
        assertEquals(url, builder.toString());
        builder.addPath("/example");
        assertEquals(expected, builder.toString());
    }
}

"151970920 de" Résumé: https://gist.github.com/enginer/230e2dc2f1d213a825d5

0
répondu Sllouyssgort 2014-10-10 15:30:38

pour android assurez-vous d'utiliser .appendPath() de android.net.Uri

0
répondu Roman Gherta 2017-02-20 09:31:18