本文介绍了是否有用于处理构建URL的Java包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找的是Java中的一些代码,它将采用 Map 对象并将其转换为查询字符串,我可以附加到我返回的URL 。我确信有一个库可以做到这一点以及更多,但我无法通过快速谷歌搜索找到它。有人知道会这样做吗?

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'm sure there's a library that does this and much more, but I can't find it with a quick Google search. Anyone know of one that will do this?

推荐答案

我找到了是一个可靠的多功能库,用于处理Java中的HTTP。但是,这是一个示例类,可能足以构建URL查询字符串:

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; }
}

用法:

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"

这篇关于是否有用于处理构建URL的Java包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:52