java将map拼接成“参数=值&参数=值”

Java将Map拼接成“参数=值&参数=值”

  把一个map的键值对拼接成“参数=值&参数=值”即“username=angusbao&password=123456”这种形式方便传递,尤其是在接口调用的时候,这种方式使用的更加普遍,比如http请求的get方式,如何用java对其进行解决呢?
  代码如下:

  /**
  * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
  * @param params 需要排序并参与字符拼接的参数组
  * @return 拼接后字符串
  * @throws UnsupportedEncodingException
  */
  public static String createLinkStringByGet(Map<String, String> params) throws UnsupportedEncodingException {
    List<String> keys = new ArrayList<String>(params.keySet());
    Collections.sort(keys);
    String prestr = "";
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      String value = params.get(key);
      value = URLEncoder.encode(value, "UTF-8");
      if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符
        prestr = prestr + key + "=" + value;
      } else {
        prestr = prestr + key + "=" + value + "&";
      }
    }
    return prestr;
  }
  public static void main(String[] args) throws UnsupportedEncodingException {
    Map<String,String> map= new HashMap<String,String>();
    map.put("1", "hello");
    map.put("2", "world");
    System.out.println(createLinkStringByGet(map));
  }

  

  最后结果为:1=hello&2=world

 

posted @ 2017-10-25 14:09  流年煮雪  阅读(23804)  评论(2编辑  收藏  举报