如何使用Java将文档上载到SharePoint?
我正在用Java创建一些大文件(DB导出),我需要将它们放在SharePoint服务器上的某个位置。现在,我正在用IE来做这件事,但我也想自动化这一步 我在网上搜索了一下,找到了一些使用SOAP的提示,但我还没有真正了解这一切的实质。有人能提供一些示例代码或食谱给我我需要做什么吗 请注意:SharePoint服务器要求NT域身份验证。我甚至无法使用Firefox登录:( 编辑如何使用Java将文档上载到SharePoint?,java,sharepoint,soap,upload,Java,Sharepoint,Soap,Upload,我正在用Java创建一些大文件(DB导出),我需要将它们放在SharePoint服务器上的某个位置。现在,我正在用IE来做这件事,但我也想自动化这一步 我在网上搜索了一下,找到了一些使用SOAP的提示,但我还没有真正了解这一切的实质。有人能提供一些示例代码或食谱给我我需要做什么吗 请注意:SharePoint服务器要求NT域身份验证。我甚至无法使用Firefox登录:( 编辑 如何将IE中可怕的URL转换为WebDAV路径 在我用我的代码破坏生产系统之前,是否有一个WebDAV“explore
- 如何将IE中可怕的URL转换为WebDAV路径
- 在我用我的代码破坏生产系统之前,是否有一个WebDAV“explorer”可以使用?我从中尝试了“DAV explorer 0.91”,但无法连接(可能是因为NT域身份验证)
- 将文档库映射到文件驱动器,并像文件系统中的任何其他文件一样保存该文件
- 使用HTTP WebDAV协议
http:///_vti_bin/
在您的情况下,您可能需要(http:///_vti_bin/Lists.asmx
)。您可以从http:///_vti_bin/Lists.asmx?WSDL
。WSS 3.0 SDK提供了有关如何使用web服务的详细信息(您可能需要使用UpdateListItems
和AddAttachment
方法)
综上所述,Sacha的第一个选项(将文档库映射到驱动器)可能是假设您可以绕过NTLM问题的最简单的方法
如果您使用的是Windows,则只需导航到文档库的UNC路径即可。例如,如果文档库的浏览器URL为:
http:///Foo/BarDocs/Forms/AllItems.aspx
您只需在Windows资源管理器地址栏中键入相应的UNC路径:
\\\Foo\BarDocs
然后将文件拖放到此位置。如果愿意,可以使用Windows资源管理器或SUBST.EXE命令行实用程序将此位置映射到驱动器号。好的……经过几个小时的工作并仔细阅读“文档”MicroSoft提供了所有提示,并且所有提示都随机分布在网络上。我已经设法编写了一些示例代码来浏览SharePoint服务器的内容:
下一站:上传内容。另一个解决方案是使用HTTP PUT方法将文件直接发送到Sharepoint 为此,您可以使用Apache HTTP客户端:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.3</version>
</dependency>
使用身份验证执行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) {
//...
}
我想我的方法可能会对你有所帮助 最初,我创建了sharepoint帐户,并按照此链接()中的过程获取REST API所需的凭据。获得凭据后,我只需要以下依赖项和代码:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
org.apache.httpcomponents
httpclient
4.5
因为我使用了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;
}
获取访问令牌的OAuth2身份验证*/
公共字符串getSharePointAccessToken()引发ClientProtocolException,IOException
{
/*初始化变量*/
字符串grant\u type=RcConstants.grant\u type;
字符串client_id=RcConstants.client_id;
字符串client\u secret=RcConstants.client\u secret;
字符串资源=RcConstants.resource;
字符串url=RcConstants.OAUTH_url+RcConstants.url_参数+“/tokens/OAUTH/2”;
/*
*注意:RcConstants.OAUTH_URL=
* https://accounts.accesscontrol.windows.net/ RcConstants.URL\u参数
*=来自的承载域
* (http://www.ktskumar.com/2017/01/access-sharepoint-online-using-
*邮递员/)图6。
*/
/*构建URL*/
HttpClient client=HttpClientBuilder.create().build();
HttpPost=新的HttpPost(url);
post.setHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
/*添加URL参数*/
List urlParameters=new ArrayList();
添加(新的BasicNameValuePair(“grant_类型”,grant_类型));
添加(新的BasicNameValuePair(“客户端id”,客户端id));
添加(新的BasicNameValuePair(“client_secret”,client_secret));
添加(新的BasicNameValuePair(“资源”,resource));
setEntity(新的UrlEncodedFormEntity(urlParameters));
/*执行post请求*/
HttpResponse response=client.execute(post);
logger.debug(“响应代码:+Response.getStatusLine().getStatusCode());
String json_String=EntityUtils.toString(response.getEntity());
JSONObject temp1=新的JSONObject(json_字符串);
if(temp1!=null)
{
/*返回访问令牌*/
返回temp1.get(“访问令牌”).toString();
}
返回RcConstants.OAUTH_FAIL_消息;
}
获得访问令牌后,我们可以使用以下方法上载:
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;
}
公共字符串putRecordInSharePoint(文件文件)抛出ClientProtocolException,IOException
{
/*令牌变量声明*/
字符串标记=getSharePointAccessToken();
/*无效或失败检查*/
if(!token.equalsIgnoreCase(RcConstants.OAUTH\u FAIL\u MESSAGE))
{
/*上载路径和文件名声明*/
字符串Url_parameter=“添加(Url=”+file.getName()+”,overwrite=true)”;
字符串url=RcConstants.UPLOAD\u FOLDER\u url+url\u参数;
/*
*注意:RcConstants.UPLOAD\u文件夹\u URL=
* https://.sharepoint.com/_api/web/
*GetFolderByServerRelativeUrl(“/Shared%20Documents/”)/
*档案/
*/
/*构建URL*/
HttpClient client=HttpClientBuilder.create().build();
HttpPost=新的HttpPost(url);
post.setHeader(“授权”、“承载人”+令牌);
/* 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;
}
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;
}
}
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-win</artifactId>
<version>4.4</version>
</dependency>