有没有正确的方法来构建URL? [英] Is there a right way to build a URL?

查看:121
本文介绍了有没有正确的方法来构建URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用的大部分代码中都有可怕的东西,例如:

In much of the code I work with there is horrible stuff like:

String url = "../Somewhere/SomeServlet?method=AMethod&id="+object.getSomething()+ "&aParam="+object.getSomethingElse());

或 - 更糟糕的是:

String url = "Somewhere/Here/Something.jsp?path="+aFile.toString().replace("\\","/")+ "&aParam="+object.getSomethingElse());

有没有正确的方法:


  1. 创建一个新网址(或者是一个URI)。

  2. 向其添加正确的转义参数。

  3. 添加这些参数中格式良好的文件路径。

  4. 将其解析为字符串。

  1. Create a new URL (or is it a URI).
  2. Add correctly escaped parameters to it.
  3. Add well-formed file paths in those params.
  4. Resolve it to a String.

基本上 - 构建字符串太容易了,而不是正确地完成它。有没有办法正确这就像构建字符串一样简单?

Essentially - it is too easy to just build the string than it is to do it properly. Is there a way to do it properly that is as easy as just building the string?

已添加

为了清楚起见 - 经过一番思考后 - 我想我正在寻找类似的东西:

For clarity - and after a little thought - I suppose I am looking for something like:

String s = new MyThing()
    .setPlace("Somewhere/Something.jsp")
    .addParameter(aName,aValue)
    .addParameter(aName,aFile)
    .toString();

这样它可以解决所有令人不快的逃避和添加?/& 并将\更改为/而不是将\更改为文件等。

so that it will deal with all of the unpleasantness of escaping and adding "?"/"&" and changing "\" to "/" instead of using "\" for files etc.

如果我必须自己编写一个(即如果Apache不是选项)是否有真正的Java技术来正确地转义各个部分。我的意思是在参数中将转换为。而在其他地方逃避%20。

If I have to write one myself (i.e. if Apache is not an option) are there real Java techniques for correctly escaping the various parts. I mean things like escaping " " in parameters as "." while escaping " " in other places a "%20".

推荐答案

我已经写完了,你可以在那里改变它想要额外的功能。它不使用任何外部资源,如果我查看过某些内容,请告诉我!

I have written this up, you can change it where you want extra functionality. It doesn't use any external resources, let me know if I have looked over something!

它基本上是 URI 类,允许您更轻松地向URI添加子目录和参数。如果您对某些内容不感兴趣,可以设置默认值。

It's basically a wrapper for the URI class that allows you to more easily add subdirectories and parameters to the URI. You can set default values if you're not interested in some things.

编辑:我添加了一个使用相对URI的选项(根据您的问题)。

I have added an option to use a relative URI (per your question).

public class Test {
    public static void main(String[] args) throws URISyntaxException,
            MalformedURLException {
        URLBuilder urlb = new URLBuilder("www.example.com");
        urlb.setConnectionType("http");
        urlb.addSubfolder("somesub");
        urlb.addSubfolder("anothersub");
        urlb.addParameter("param lol", "unknown");
        urlb.addParameter("paramY", "known");
        String url = urlb.getURL();
        System.out.println(url);


        urlb = new URLBuilder();
        urlb.addSubfolder("servlet");
        urlb.addSubfolder("jsp");
        urlb.addSubfolder("somesub");
        urlb.addSubfolder("anothersub");
        urlb.addParameter("param lol", "unknown");
        urlb.addParameter("paramY", "known");
        String relUrl = urlb.getRelativeURL();
        System.out.println(relUrl);
    }
}

class URLBuilder {
    private StringBuilder folders, params;
    private String connType, host;

    void setConnectionType(String conn) {
        connType = conn;
    }

    URLBuilder(){
        folders = new StringBuilder();
        params = new StringBuilder();
    }

    URLBuilder(String host) {
        this();
        this.host = host;
    }

    void addSubfolder(String folder) {
        folders.append("/");
        folders.append(folder);
    }

    void addParameter(String parameter, String value) {
        if(params.toString().length() > 0){params.append("&");}
        params.append(parameter);
        params.append("=");
        params.append(value);
    }

    String getURL() throws URISyntaxException, MalformedURLException {
        URI uri = new URI(connType, host, folders.toString(),
                params.toString(), null);
        return uri.toURL().toString();
    }

    String getRelativeURL() throws URISyntaxException, MalformedURLException{
        URI uri = new URI(null, null, folders.toString(), params.toString(), null);
        return uri.toString();
    }
}

输出:

绝对


http://www.example.com/somesub/anothersub?param%20lol=unknown&paramY=known

相对


/ servlet / jsp / somesub / anothersub?param%20lol = unknown& paramY = known

/servlet/jsp/somesub/anothersub?param%20lol=unknown&paramY=known

这篇关于有没有正确的方法来构建URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆