我正在尝试编写Java代码以从Liferay服务器下载文件。我找到了这个例子,但我不知道在哪里插入目标网址:
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
,那么如何创建此请求并将其链接到我的网址?
答案 0 :(得分: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
}