Search code examples
javaxmlurldecode

Get specified parameter from encoded url paramters String with java


Note that what I want is not get specified parameter in a sevlet, but to get the parameter from a String like that:

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

It's a url encoded utf-8 string, when decode this by python I can get the real data it represents:

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

I want to get the parameter res_data that I care about, more specifically, I just want the request_token in the xml of res_data

I know I can use regex to get this work, but is there a more suitable way to use some lib like apache url lib or something else that I can get the res_data parameter more elegantly? May be stealing some components from servlet mechanism?


Solution

  • Since you say you don't want to hack it with a regex you might use a proper XML parser, although for such a small example it is probably overkill.

    If you can assume that you can simply split your string on &'s, i.e., there aren't any &'s in there that do not signal the boundary of two attribute-value pairs, you can first decode the string, then extract the attribute-value pairs from it and finally use a DOM parser + XPath to get to the request token:

    // 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);
    }