【问题标题】:template parsing URL in javajava中的模板解析URL
【发布时间】:2013-06-13 08:18:19
【问题描述】:

我有一个应用程序从 SMPP 服务器接收消息并将收到的消息转发给用户 Web 服务。所有用户在数据库中都有一个这样的 URL:

http://www.example.com/get.php?from=${originator}&to=${destination}&data=${content}
http://www.example.com/submit?origin=${originator}&dst=${destination}&cnt=${content}

它们的模式中都有${originator},${destination},${content}。他们的 URL 中可能有其他参数,也可能没有。从数据库获取用户 URL 后,我使用 Jodd StringTemplateParser 替换上述参数:

private StringTemplateParser stp = new StringTemplateParser();
private final Map<String, String> args = new HashMap<>();

args.put("originator", msg.getOriginator());
args.put("destination", msg.getDestination());
args.put("content", msg.getContent());

String result = stp.parse(deliveryUrl, new MacroResolver() {
    @Override
    public String resolve(String macroName) {
        return args.get(macroName);
    }
});

然后我使用 apache http 客户端调用用户 URL:

URL url = new URL(result);
int port = url.getPort();
uri = new URI(url.getProtocol(), null, url.getHost(), port == -1 ? 80 : port, url.getPath(), url.getQuery(), null);

DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = null;
try {
    request = new HttpGet(uri);
    client.execute(request)
} catch (Exception ex) {
    if (request != null) {
        request.releaseConnection();
    }
}

我尝试进行一些编码,因为用户可能会发送包含%$&amp; 等字符的任何文本。问题是当content 包含类似hello&amp;x=2&amp;c=3243 的内容时,用户只能得到helloURI 类将其视为常规 GET 查询参数。任何人都可以帮忙吗?

【问题讨论】:

    标签: java query-string httpclient string-parsing jodd


    【解决方案1】:

    在构建新 URI 时,您需要对参数值进行编码。

    您可以使用URLEncoder.encode(String) 对参数进行编码。

    所以,在您的 MacroResolver 中,只需返回 URLEncoder.encode(map.get(macroName))

    【讨论】:

      【解决方案2】:

      我认为在您的情况下,您需要为您的代码使用类似这样的 HTTP 默认内容字符集

      request = new HttpGet(url+"?"+URLEncodedUtils.format(namevaluepair, HTTP.DEFAULT_CONTENT_CHARSET));

      【讨论】:

        猜你喜欢
        • 2014-07-20
        • 1970-01-01
        • 2014-03-16
        • 2016-12-25
        • 1970-01-01
        • 2016-12-18
        • 1970-01-01
        • 1970-01-01
        • 2019-05-23
        相关资源
        最近更新 更多