另一种解决方法是使用 http 请求获取文件。
以下示例使用 Apache commons-httpclient (v4) 和基本身份验证。如果客人有权查看文件,则不需要身份验证部分。
对于基本身份验证,您需要 com.liferay.portal.security.auth.BasicAuthHeaderAutoLogin
作为属性中的登录钩子之一auto.login.hooks
(在 portal-ext.properties 中)
例子
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
private static byte[] getFile(inal long groupId, final long folderId, final String title, final String hostname, final int port, final String username, final String password) throws ClientProtocolException, IOException {
final DefaultHttpClient httpclient = new DefaultHttpClient();
try {
final String filename = URLEncoder.encode(title);
final HttpHost targetHost = new HttpHost(hostname, port);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
final AuthScope authscope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
httpclient.getCredentialsProvider().setCredentials(authscope, creds);
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
final HttpGet httpget = new HttpGet("/documents/" + groupId + "/" + folderId + "/" + filename);
final HttpResponse response = httpclient.execute(targetHost, httpget, localContext);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final HttpEntity entity = response.getEntity();
if (entity != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toByteArray();
}
}
return null;
} finally {
httpclient.getConnectionManager().shutdown();
}
}
从您从 Web 服务获得的 FileEntry 中,您可以获得 groupId、folderId 和 title 并调用该方法