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

java sharepoint soap upload

31163 观看

7回复

242808 作者的声誉

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

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

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

编辑

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

回应 (7)


1

1484 作者的声誉

我可以想到不同的选择:

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

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

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

作者: sachaa 发布者: 24.11.2008 02:30

7

3970 作者的声誉

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

在您的情况下,您可能需要列表Web服务http://<Site>/_vti_bin/Lists.asmx)。你可以从中获取WSDL http://<Site>/_vti_bin/Lists.asmx?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命令行实用程序将此位置映射到驱动器号。

作者: dariom 发布者: 24.11.2008 03:29

3

242808 作者的声誉

决定

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

下一站:上传一些东西。

作者: Aaron Digulla 发布者: 26.11.2008 02:56

3

151 作者的声誉

另一种解决方案是使用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());
    }
}

参考

使用身份验证执行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) {
      //...
    }
作者: DMEx38 发布者: 24.04.2013 09:51

1

134 作者的声誉

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

最初我创建了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;
}
作者: Monkey D. Luffy 发布者: 20.09.2017 02:49

1

11 作者的声誉

我设法使用集成的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</artifactId>
    <version>4.5</version>
</dependency>

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

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

作者: go4X 发布者: 07.06.2018 01:35

0

1 作者的声誉

@Monkey D. Luffy

什么是RcConstants ???

String grant_type = RcConstants.GRANT_TYPE; 例如

作者: Nicolas Piccolo Zanni 发布者: 22.11.2018 08:07
32x32