如何使用Java将文档上载到SharePoint?

我正在使用Java创建一些大文件(数据库导出),我需要将它们放在我们的SharePoint服务器上。 现在,我正在用IE做这个,但我也希望自动执行这一步骤。

我搜索了网页,我发现了一些使用SOAP的提示,但我还没有真正看到所有这些。 有人能为我提供一些示例代码或配方,我需要做什么吗?

请注意:SharePoint服务器要求进行NT域身份validation。 我甚至无法使用Firefox登录:(

编辑

  • 如何将IE中的可怕URL转换为WebDAV路径?
  • 是否有一个WebDAV“资源管理器”,我可以在使用我的代码破坏生产系统之前使用它? 我试过http://www.davexplorer.org/的 “DAV Explorer 0.91”,但无法连接(可能是因为NT域名validation)。

除了Sacha的建议 ,您还可以使用SharePoint SOAP Web服务。 每个SharePoint站点都通过路径http:///_vti_bin/公开了一堆Web服务。

在您的情况下,您可能需要列表Web服务 ( http:///_vti_bin/Lists.asmx )。 您可以从http:///_vti_bin/Lists.asmx?WSDL获取WSDL。 WSS 3.0 SDK详细介绍了如何使用Web服务(您可能希望使用UpdateListItemsAddAttachment方法)。

所有这一切,Sacha的第一个选择(将文档库映射到驱动器)可能是最简单的方法,假设您可以解决NTLM问题。

如果您使用的是Windows,则只需导航到文档库的UNC路径即可。 例如,如果文档库的浏览器URL是:

http:///Foo/BarDocs/Forms/AllItems.aspx

您只需在Windows资源管理器地址栏中键入相应的UNC路径:

\\\Foo\BarDocs

然后将文件拖放到此位置。 如果您愿意,可以使用Windows资源管理器或SUBST.EXE命令行实用程序将此位置映射到驱动器号。

好的…经过几个小时的工作,咬住自己通过“文档”MicroSoft提供并随机传播到网络上的所有提示,我设法编写了一些示例代码来浏览SharePoint服务器的内容: 导航SharePoint Axis2的文件夹 。

下一站:上传一些东西。

另一种解决方案是使用HTTP PUT方法将文件直接发送到Sharepoint。

为此,您可以使用Apache HTTP Client

  org.apache.httpcomponents httpclient 4.2.3  

要允许NTLMv2身份validation,您需要JCIF库。

  jcifs jcifs 1.3.17  

首先,我们需要编写一个包装器,以允许Apache HTTP Client使用JCIF进行NTLMv2支持:

 public final class JCIFSEngine implements NTLMEngine { private static final int TYPE_1_FLAGS = NtlmFlags.NTLMSSP_NEGOTIATE_56 | NtlmFlags.NTLMSSP_NEGOTIATE_128 | NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2 | NtlmFlags.NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NtlmFlags.NTLMSSP_REQUEST_TARGET; @Override public String generateType1Msg(final String domain, final String workstation) throws NTLMEngineException { final Type1Message type1Message = new Type1Message(TYPE_1_FLAGS, domain, workstation); return Base64.encode(type1Message.toByteArray()); } @Override public String generateType3Msg(final String username, final String password, final String domain, final String workstation, final String challenge) throws NTLMEngineException { Type2Message type2Message; try { type2Message = new Type2Message(Base64.decode(challenge)); } catch (final IOException exception) { throw new NTLMEngineException("Invalid NTLM type 2 message", exception); } final int type2Flags = type2Message.getFlags(); final int type3Flags = type2Flags & (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER)); final Type3Message type3Message = new Type3Message(type2Message, password, domain, username, workstation, type3Flags); return Base64.encode(type3Message.toByteArray()); } } 

参考

使用身份validation执行HTTP PUT的主要代码:

  try { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); DefaultHttpClient httpclient = new DefaultHttpClient(params); //Register JCIF NTLMv2 to manage ntlm auth. httpclient.getAuthSchemes().register("ntlm", new AuthSchemeFactory() { @Override public AuthScheme newInstance(HttpParams hp) { return new NTLMScheme(new JCIFSEngine()); } }); //Provide login/password httpclient.getCredentialsProvider().setCredentials( AuthScope.ANY, new NTCredentials([LOGIN], [PASSWORD], "", [DOMAIN])); //Create HTTP PUT Request HttpPut request = new HttpPut("http://[server]/[site]/[folder]/[fileName]"); request.setEntity(new FileEntity([File])); return httpclient.execute(request); } catch (IOException ex) { //... } 

我可以想到不同的选择:

  • 将文档库映射到文件驱动器,只需像文件系统中的任何其他文件一样保存文件。
  • 使用HTTP WebDAV协议。

…以及NTLM身份validation部分:

http://www.luigidragone.com/networking/ntlm.html

我认为我的方法可能对你有帮助。

最初我创建了sharepoint帐户,并按照此链接( http://www.ktskumar.com/2017/01/access-sharepoint-online-using-postman/ )中的步骤获取REST API所需的凭据。 一旦我获得了凭据,我需要的是以下依赖项和代码:

  org.apache.httpcomponents httpclient 4.5  

由于我使用了OAUTH2身份validation,因此获取访问令牌的代码有助于其他CRUD操作。

 /* OAuth2 authentication to get access token */ public String getSharePointAccessToken() throws ClientProtocolException, IOException { /* Initializing variables */ String grant_type = RcConstants.GRANT_TYPE; String client_id = RcConstants.CLIENT_ID; String client_secret = RcConstants.CLIENT_SECRET; String resource = RcConstants.RESOURCE; String url = RcConstants.OAUTH_URL + RcConstants.URL_PARAMETER + "/tokens/OAuth/2"; /* * NOTE: RcConstants.OAUTH_URL = * https://accounts.accesscontrol.windows.net/ RcConstants.URL_PARAMETER * = Bearer Realm from * (http://www.ktskumar.com/2017/01/access-sharepoint-online-using- * postman/) Figure 6. */ /* Building URL */ HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); /* Adding URL Parameters */ List urlParameters = new ArrayList(); urlParameters.add(new BasicNameValuePair("grant_type", grant_type)); urlParameters.add(new BasicNameValuePair("client_id", client_id)); urlParameters.add(new BasicNameValuePair("client_secret", client_secret)); urlParameters.add(new BasicNameValuePair("resource", resource)); post.setEntity(new UrlEncodedFormEntity(urlParameters)); /* Executing the post request */ HttpResponse response = client.execute(post); logger.debug("Response Code : " + response.getStatusLine().getStatusCode()); String json_string = EntityUtils.toString(response.getEntity()); JSONObject temp1 = new JSONObject(json_string); if (temp1 != null) { /* Returning access token */ return temp1.get("access_token").toString(); } return RcConstants.OAUTH_FAIL_MESSAGE; } 

获得访问令牌后,我们可以使用以下方法上传:

 public String putRecordInSharePoint(File file) throws ClientProtocolException, IOException { /* Token variable declaration */ String token = getSharePointAccessToken(); /* Null or fail check */ if (!token.equalsIgnoreCase(RcConstants.OAUTH_FAIL_MESSAGE)) { /* Upload path and file name declaration */ String Url_parameter = "Add(url='" + file.getName() + "',overwrite=true)"; String url = RcConstants.UPLOAD_FOLDER_URL + Url_parameter; /* * NOTE: RcConstants.UPLOAD_FOLDER_URL = * https://.sharepoint.com/_api/web/ * GetFolderByServerRelativeUrl('/Shared%20Documents/')/ * Files/ */ /* Building URL */ HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.setHeader("Authorization", "Bearer " + token); post.setHeader("accept", "application/json;odata=verbose"); /* Declaring File Entity */ post.setEntity(new FileEntity(file)); /* Executing the post request */ HttpResponse response = client.execute(post); logger.debug("Response Code : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()|| response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value()) { /* Returning Success Message */ return RcConstants.UPLOAD_SUCCESS_MESSAGE; } else { /* Returning Failure Message */ return RcConstants.UPLOAD_FAIL_MESSAGE; } } return token; } 

我设法使用集成的Windows标识,使用此代码将文件下载到sharepoint,这可能会有所帮助。

 public class HttpClient { HttpClient() { } public static void download(final String source, final File resultingFile) { CloseableHttpClient client = WinHttpClients.createSystem(); HttpGet httpRequest = new HttpGet(source); CloseableHttpResponse httpResponse = null; try { httpResponse = client.execute(httpRequest); HttpEntity entity = httpResponse.getEntity(); if(httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { LOGGER.warn(httpResponse.getStatusLine()); }else { LOGGER.debug(httpResponse.getStatusLine()); FileUtils.touch(resultingFile); InputStream is = entity.getContent(); File outFile = new File(resultingFile.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(outFile); int inByte; while ((inByte = is.read()) != -1) { fos.write(inByte); } is.close(); fos.close(); client.close(); } } catch (ClientProtocolException e) { LOGGER.warn(e); } catch (UnsupportedOperationException e) { LOGGER.warn(e); } catch (IOException e) { LOGGER.warn(e); } } public static void upload(final File source, final String destination) { CloseableHttpClient httpclient = WinHttpClients.createSystem(); HttpPut httpRequest = new HttpPut(destination); httpRequest.setEntity(new FileEntity(new File(source.getPath()))); CloseableHttpResponse httpResponse = null; try { httpResponse = httpclient.execute(httpRequest); EntityUtils.consume(httpResponse.getEntity()); if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { LOGGER.debug(httpResponse.getStatusLine()); LOGGER.info("Upload of " + source.getName() + " via HTTP-Client succeeded."); } else if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LOGGER.debug(httpResponse.getStatusLine()); }else { LOGGER.warn("Uploading " + source.getName() + " failed."); LOGGER.warn(httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase()); } } catch (IOException e) { LOGGER.warn(e); LOGGER.warn(e.getMessage()); } return; } } 

WinHttpClients:

  org.apache.httpcomponents httpclient 4.5  

路径:
org.apache.http.impl.client.WinHttpClients

描述:
CloseableHttpClient实例的工厂方法,默认情况下配置为使用集成Windows身份validation。