Exchange Web服务(EWS)Java Api:401未经授权

时间:2016-09-29 12:25:00

标签: java api exchange-server exchangewebservices

当我尝试连接到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,域和网址)进行了测试,效果非常好。

这是我的实际代码:

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 个答案:

答案 0 :(得分:0)

这是一个很好的问题,但我找到了解决问题的另一种方法!

首先,您应该导入jar ews-java-api-2.0.jar。如果你使用maven,你可以将以下代码添加到pom.xml

<dependency>
  <groupId>com.microsoft.ews-java-api</groupId>
  <artifactId>ews-java-api</artifactId>
  <version>2.0</version>
</dependency>

其次,您应该使用名为MailUtil.java的新java类。默认情况下,某些Exchange Server不启动SMTP服务,因此我们使用Microsoft Exchange WebServices(EWS)代替SMTP服务。

MailUtil.java

package com.spacex.util;


import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

/**
 * Exchange send email util
 *
 * @author vino.dang
 * @create 2017/01/08
 */
public class MailUtil {

    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);



    /**
     * send emial
     * @return
     */
    public static boolean sendEmail() {

        Boolean flag = false;
        try {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // your server version
            ExchangeCredentials credentials = new WebCredentials("vino", "abcd123", "spacex"); // change them to your email username, password, email domain
            service.setCredentials(credentials);
            service.setUrl(new URI("https://outlook.spacex.com/EWS/Exchange.asmx")); //outlook.spacex.com change it to your email server address
            EmailMessage msg = new EmailMessage(service);
            msg.setSubject("This is a test!!!"); //email subject
            msg.setBody(MessageBody.getMessageBodyFromText("This is a test!!! pls ignore it!")); //email body
            msg.getToRecipients().add("123@hotmail.com"); //email receiver
//        msg.getCcRecipients().add("test2@test.com"); // email cc recipients
//        msg.getAttachments().addFileAttachment("D:\\Downloads\\EWSJavaAPI_1.2\\EWSJavaAPI_1.2\\Getting started with EWS Java API.RTF"); // email attachment
            msg.send(); //send email
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;

    }


    public static void main(String[] args) {

        sendEmail();

    }
}

答案 1 :(得分:0)

这是我的有效代码。仅当调用EWS时,登录才会发生。当我为Exchange编写emailValidService时。我遇到了同样的错误,我尝试了很多小时,然后才发现问题出在哪里。我在调用EWS时使用了subscriptionToPullNotifications()函数。

如果我不调用this.pullEmailNotifications(),则这段代码无法正常工作。

public  Boolean checkEmailValid(String username, String password, String uri, String  service_name) {
    ExchangeVersion en = ExchangeVersion.valueOf(service_name);
    logger.info("******checkEmailValid service  ************:  "  +en);
    ExchangeService service = new ExchangeService( en);
    ExchangeCredentials credentials = new WebCredentials(username,password); 
    service.setCredentials(credentials);
    logger.info("*** checkEmailValid USERNAME : " + username);
    logger.info("**** checkEmailValid PASSWORD : " + password);

    try {
        service.setUrl(new URI(uri));
        service.validate();
        return this.pullEmailNotifications(service);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        logger.error("login failed : " + e1.getLocalizedMessage());
        e1.printStackTrace();
        return false;
    }
}



     @SuppressWarnings({ "unchecked", "rawtypes" })
    public  boolean pullEmailNotifications(ExchangeService service) throws 
     Exception {
     try {
          logger.info("pullEmailNotifications");
          List folder = new ArrayList();        


     folder.add(FolderId.getFolderIdFromWellKnownFolderName 
     (WellKnownFolderName.Inbox));
    logger.info("folder creatd : " + folder.size());
    PullSubscription subscription = service.
            subscribeToPullNotifications(folder, 5, null, EventType.Created/* , EventType.Created, EventType.Deleted */);
    logger.info("Adding pull subscription");
    GetEventsResults events = subscription.getEvents();
    for (ItemEvent itemEvent : events.getItemEvents()) {
        logger.info("Event recieved");
        // if (itemEvent.getEventType()== EventType.NewMail) {
        logger.info("New Mail");
        EmailMessage message = EmailMessage.bind(service, itemEvent.getItemId());
        logger.info("Adding message " + message);

    }
    logger.info("Adding pull events" + events);

    return true; 
    }catch(Exception e) {
        logger.error("pull notification failed : " + e.getLocalizedMessage());

        e.printStackTrace();
        return false;
    }
}