0

我正在尝试编写 Java 代码以从 Liferay 服务器下载文件。我找到了这个例子,但我不知道在哪里插入目标 URL:

static Object setRequest(){

    static String getURL(HttpServletRequest req) {

        String scheme = req.getScheme();             // http
        String serverName = req.getServerName();     // hostname.com
        int serverPort = req.getServerPort();        // 80
        String contextPath = req.getContextPath();   // /mywebapp
        String servletPath = req.getServletPath();   // /servlet/MyServlet
        String pathInfo = req.getPathInfo();         // /a/b;c=123
        String queryString = req.getQueryString();   // d=789

        // Reconstruct original requesting URL
        StringBuffer url =  new StringBuffer();
        url.append(scheme).append("://").append(serverName);

        if ((serverPort != 80) && (serverPort != 443)) {
            url.append(":").append(serverPort);
        }

        url.append(contextPath).append(servletPath);

        if (pathInfo != null) {
            url.append(pathInfo);
        }
        if (queryString != null) {
            url.append("?").append(queryString);
        }
        return url.toString();
    }
}

正如您可能看到的那样,此类需要一个HttpServletRequest,那么如何创建此请求并将其链接到我的 URL?

4

1 回答 1

0
String urlname = "";//You set your url path for the file 
URL url = new URL(urlname);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() == 200) {
   InputStream stream = con.getInputStream();
   // now you can read the read the data
}
于 2013-11-01T10:32:30.563 回答