• URI获取请求参数


    一、业务场景

    获取类似http://120.0.0.1:8080/receiveState?timeStamp=1586937885&number=2这样的请求uri中的某些参数

    二、解决方法

    处理思想:

    根据uri字符串的规律,三次切割。第一次获取路径和多个参数连接字符串,继续切割参数字符串,获取单个参数键值对,最后切割键值对拿取参数值

    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class UriSplitTest {
    
        public static Map<String, List<String>> getQueryParams(String url) {
            try {
                Map<String, List<String>> params = new HashMap<String, List<String>>();
                String[] urlParts = url.split("\?");//这里分割uri成请求路径和请求参数两部分,注意这里的?不能直接作为分隔符,需要转义
                if (urlParts.length > 1) {
                    String query = urlParts[1];//获取到参数字符串
                    for (String param : query.split("&")) {
                        String[] pair = param.split("=");
                        String key = URLDecoder.decode(pair[0], "UTF-8");
                        String value = "";
                        if (pair.length > 1) {
                            value = URLDecoder.decode(pair[1], "UTF-8");
                        }
    
                        List<String> values = params.get(key);
                        if (values == null) {
                            values = new ArrayList<String>();
                            params.put(key, values);
                        }
                        values.add(value);
                    }
                }
    
                return params;
            } catch (UnsupportedEncodingException ex) {
                throw new AssertionError(ex);
            }
        
        }
        
        public static void main(String[] args) {
            String uri = "http://120.0.0.1:8080/receiveState?timeStamp=1586937885&number=2";
            Map<String, List<String>> params = getQueryParams(uri);
            System.out.println(params.toString());//{timeStamp=[1586937885], number=[2]}
        }
    
    }
  • 相关阅读:
    The user specified as a definer (”@’%') does not exist解决方法
    mongodb下载地址
    镜像系统,超好用
    部署mysql后,无法设置用户远程登陆(%只所有用户,不可以,只能给指定的ip?)
    Libcap的简介及安装
    GCC命令基础
    gcc安装(centos)
    React Native 踩坑
    webpack 和 babel
    React 开发笔记
  • 原文地址:https://www.cnblogs.com/Mr-k404/p/12906352.html
Copyright © 2020-2023  润新知