How to build url in java?

前端 未结 2 367
礼貌的吻别
礼貌的吻别 2020-12-29 19:08

I am building a String with StringBuilder

StringBuilder builder = new StringBuilder();
builder.append(\"my parameters\");
builder.append(\"other parameters\"         


        
相关标签:
2条回答
  • 2020-12-29 19:16

    Try apache's URIBuilder : [Documentation]

    import org.apache.http.client.utils.URIBuilder;
    
    // ...
    
    URIBuilder b = new URIBuilder("http://example.com");
    b.addParameter("t", "search");
    b.addParameter("q", "apples");
    
    Url url = b.build().toUrl();
    

    Maven dependency:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    
    0 讨论(0)
  • 2020-12-29 19:26

    Since you want to create the URL and consume it through a GET request, it would be better to use a library that helps you in this process. You can use HttpComponents or another library like Unirest that is built on top of HttpComponents which ease all this work.

    Here's an example using Unirest:

    HttpResponse<String> stringResponse = Unirest.get("https://www.youtube.com/results")
        .field("search_query", "eñe")
        .asString();
    System.out.println(stringResponse.getBody());
    

    This will retrieve the HTML response corresponding to all the results from a search on youtube using "eñe". The ñ character will be encoded for you.

    DISCLAIMER: I'm not attached to Unirest in any mean. I'm not a developer or a sponsor of this project. I'm only a happy user of this framework.

    0 讨论(0)
提交回复
热议问题