zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    网络编程中 TCP 半开连接和TIME_WAIT 学习
    redis中的小秘密和持久化小细节
    排序
    Es官方文档整理-3.Doc Values和FieldData
    Es官方文档整理-2.分片内部原理
    Elasticsearch doc_value认识
    路边停靠 贴边停车不蹭轮胎的技巧
    mybatis 连接数据库
    putIfAbsent
    Hive与HBase区别 大墨垂杨
  • 原文地址:https://www.cnblogs.com/angusbao/p/7728513.html
Copyright © 2011-2022 走看看