相信Android在做Web开发时,一定遇到过要解析路径中的参数。比如下面这个例子:
String path = "http://www.test.com/payment_m.aspx?action=confirm&order_no=on123456&order_money=99.99&return_url=test/return_url.aspx";
如果要解析其中的参数,应该怎么办呢?下面我们就以这个例子,在Android环境下做个简单的演示。
String path = "http://www.test.com/payment_m.aspx?action=confirm&order_no=on123456&order_money=99.99&return_url=test/return_url.aspx";
Uri uri = Uri.parse(path);
String action = uri.getQueryParameter("action"); //解析参数
String order_no = uri.getQueryParameter("order_no");//解析参数
String order_money = uri.getQueryParameter("order_money");//解析参数
String return_url = uri.getQueryParameter("return_url");//解析参数
String pa = uri.getLastPathSegment();//解析最后一个地址段,即payment_m.aspx
System.out.println(
"parse_uri==>"+action+"\n"
+order_no+"\n"
+order_money+"\n"
+return_url+"\n"
+pa);
运行结果:
当然除此之外,还有一些其他的实用方法
getHost(); //获得主机地址
getPathSegments(); //获得地址段集合
Uri详情可以翻墙链接:
https://developer.android.com/reference/android/net/Uri.html