当我尝试连接到Exchange服务器时,我遇到401错误:
microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException: The request failed. The request failed. The remote server returned an error: (401)Unauthorized
我测试了https://ewseditor.codeplex.com/(使用相同的userId,userPw,域和url),它完美地运行 .
这是我的实际代码:
public static void main( String[] args )
{
try {
CustomExchangeService service = new CustomExchangeService(version);
ExchangeCredentials credentials = new WebCredentials(userId, userPw,domain);
service.setUrl(new URI(url));
service.setCredentials(credentials);
service.setTraceEnabled(true);
Folder.bind( getInstance().service, WellKnownFolderName.Inbox, PropertySet.IdOnly );
} catch (Exception e) {
e.printStackTrace();
}
}
而CustomExchangeService类有这个方法:
protected Registry<ConnectionSocketFactory> createConnectionSocketFactoryRegistry() {
try {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register(EWSConstants.HTTP_SCHEME, new PlainConnectionSocketFactory())
.register(EWSConstants.HTTPS_SCHEME, EwsSSLProtocolSocketFactory.build(
null, NoopHostnameVerifier.INSTANCE
))
.build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(
"Could not initialize ConnectionSocketFactory instances for HttpClientConnectionManager", e
);
}
}
为什么我有这个错误?也许是因为SSL的事情?
谢谢你的帮助
2 回答
这是一个很好的问题,但我找到了解决它的另一种方法!
首先,你应该导入jar
ews-java-api-2.0.jar
. 如果您使用maven,您可以将以下代码添加到pom.xml
其次,您应该使用名为
MailUtil.java
的新java类 . 默认情况下,某些Exchange Server不启动SMTP
服务,因此我们使用Microsoft Exchange WebServices(EWS)
而不是SMTP
service .MailUtil.java
这是我的代码有效 . 只有在对EWS进行呼叫时,才会进行登录 . 当我为Exchange编写emailValidService时 . 我得到了同样的错误,我试了好几个小时,看到问题出在哪里 . 我使用了subscribeToPullNotifications()函数,因为它调用了EWS .
如果我不调用this.pullEmailNotifications(),代码将不起作用 .