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

时间:2008-11-24 14:21:31

标签: java sharepoint soap upload

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

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

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

修改

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

6 个答案:

答案 0 :(得分:7)

除了Sacha's suggestions之外,您还可以使用SharePoint SOAP Web服务。每个SharePoint站点都通过路径http://<Site>/_vti_bin/公开了一堆Web服务。

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

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

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

http://<Site>/Foo/BarDocs/Forms/AllItems.aspx

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

\\<Site>\Foo\BarDocs

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

答案 1 :(得分:4)

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

下一站:上传一些东西。

答案 2 :(得分:3)

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

为此,您可以使用 Apache HTTP Client

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2.3</version>
</dependency>

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

<dependency>
   <groupId>jcifs</groupId>
   <artifactId>jcifs</artifactId>
   <version>1.3.17</version>
</dependency>

首先,我们需要编写一个包装器,以允许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());
    }
}

Reference

使用身份验证执行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) {
      //...
    }

答案 3 :(得分:2)

我使用集成的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:

 <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient-win</artifactId>
     <version>4.4</version>
 </dependency> 

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

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

答案 4 :(得分:1)

我可以想到不同的选择:

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

...以及NTLM身份验证部分:

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

答案 5 :(得分:1)

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

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

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5</version>
</dependency>

由于我使用了OAUTH2身份验证,因此获取访问令牌的代码有助于其他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<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    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://<your_domain>.sharepoint.com/_api/web/
         * GetFolderByServerRelativeUrl('/Shared%20Documents/<FolderName>')/
         * 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;
}