Is there a Java package to handle building URLs?

前端 未结 3 598
孤街浪徒
孤街浪徒 2020-12-05 18:32

What I\'m looking for specifically is some code in Java that will take a Map object and convert it into a query string that I can append to a URL I return. I\'

相关标签:
3条回答
  • 2020-12-05 19:00

    I found apache httpcomponents to be a solid and versatile library for dealing with HTTP in Java. However, here's a sample class, which might suffice for building URL query strings:

    import java.net.URLEncoder;
    
    public class QueryString {
    
        private String query = "";
    
        public QueryString(HashMap<String, String> map) {
            Iterator it = mp.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry)it.next();
                query += URLEncoder.encode(pairs.getKey(), "utf-8") + "=" +
                URLEncoder.encode(pairs.getValue(), "utf-8");
                if (it.hasNext()) { query += "&"; }
            }
        }
    
        public QueryString(Object name, Object value) {
            query = URLEncoder.encode(name.toString(), "utf-8") + "=" +
                URLEncoder.encode(value.toString(), "utf-8");
        }
    
        public QueryString() { query = ""; }
    
        public synchronized void add(Object name, Object value) {
            if (!query.trim().equals("")) query += "&";
            query += URLEncoder.encode(name.toString(), "utf-8") + "=" +
                URLEncoder.encode(value.toString(), "utf-8");
        }
    
        public String toString() { return query; }
    }
    

    Usage:

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("hello", "world");
    map.put("lang", "en");
    
    QueryString q = new QueryString(map);
    System.out.println(q);
    // => "hello=world&lang=en"
    
    0 讨论(0)
  • 2020-12-05 19:02

    Try URIBuilder from Apache Http Compoments (HttpClient 4).

    It does not actually take a map, but is well suited for building URIs.

    0 讨论(0)
  • 2020-12-05 19:11

    There's this online, so you can simply call any of:

    InputStream serverInput = post(URL url, Map parameters); 
    InputStream serverInput = post(URL url, Map parameters); 
    InputStream serverInput = post(URL url, Map cookies, Map parameters); 
    InputStream serverInput = post(URL url, String[] cookies, Object[] parameters); 
    InputStream serverInput = post(URL url, Object[] parameters).
    

    He provides the source code too.

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