使用 java 从编码的 url 参数字符串中获取特定参数

Get specified parameter from encoded url paramters String with java

请注意,我想要的不是在 sevlet 中获取指定参数,而是从 String 中获取参数,例如:

res_data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf8%22%3F%3E%3Cdirect_trade_create_res%3E%3Crequest_token%3E201502051324ee4d4baf14d30e3510808c08ee1d%3C%2Frequest_token%3E%3C%2Fdirect_trade_create_res%3E&service=alipay.wap.trade.create.direct&sec_id=MD5&partner=2088611853232587&req_id=20121212344553&v=2.0

这是一个url编码的utf-8字符串,当用python解码时,我可以得到它代表的真实数据:

res_data=<?xml version="1.0" encoding="utf-8"?><direct_trade_create_res><request_token>201502051324ee4d4baf14d30e3510808c08ee1d</request_token></direct_trade_create_res>&service=alipay.wap.trade.create.direct&sec_id=MD5&partner=2088611853232587&req_id=20121212344553&v=2.0

我想获取我关心的参数res_data,更具体地说,我只想要res_dataxml中的request_token

]

我知道我可以使用正则表达式来完成这项工作,但是是否有更合适的方法来使用某些库,例如 apache url 库或其他我可以获得 res_data 参数的库优雅?可能是窃取 servlet 机制的某些组件?

您可以使用 java.net.URLDecoder。假设参数在一个名为 param 的字符串中(并且您已经将它与通过 & 连接到它的其他参数分开):

String[] splitString = param.split("=");
String realData = null;
try {
    String realData = java.net.URLDecoder.decode( splitString[1], "UTF-8" );
} catch ( UnsupportedEncodingException e ) {
    // Nothing to do, it should not happen as you supplied a standard one
}

完成后,您可以使用您选择的 XML 解析器解析它并提取您想要的任何内容。不过,不要尝试用正则表达式解析 XML。

既然你说你不想用正则表达式破解它,你可能会使用适当的 XML 解析器,尽管对于这么小的例子来说它可能有点矫枉过正。

如果您可以假设您可以简单地在 & 上拆分您的字符串,即,其中没有 不存在的任何 & 表示两个属性值对的边界,您可以先解码字符串,然后从中提取属性值对,最后使用 DOM 解析器 + XPath 获取请求令牌:

// split up URL parameters into attribute value pairs
String[] pairs = s.split("&");

// expect the first attribute/value pair to contain the data
// and decode the URL escape sequences
String resData = URLDecoder.decode(pairs[0], "utf-8");

int equalIndex = resData.indexOf("=");
if (equalIndex >= 0) {
    // the value is right of the '=' sign
    String xmlString = resData.substring(equalIndex + 1);

    // prepare XML parser
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = dbf.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(xmlString));
    Document doc = parser.parse(is);

    // prepare XPath expression to extract request token
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression xp = xpath.compile("//request_token/text()");

    String requestToken = xp.evaluate(doc);
}