BuildEwsHttpWebRequest method

Future<IEwsHttpWebRequest> BuildEwsHttpWebRequest()
Builds the IEwsHttpWebRequest object for current service request with exception handling.

Implementation

Future<IEwsHttpWebRequest> BuildEwsHttpWebRequest() async {
  IEwsHttpWebRequest? request;
  try {
    request = await Service.PrepareHttpWebRequest(GetXmlElementName());

    Service.TraceHttpRequestHeaders(
      TraceFlags.EwsRequestHttpHeaders,
      request,
    );

    bool needSignature =
        Service.Credentials != null && Service.Credentials!.NeedSignature;
    bool needTrace = Service.IsTraceEnabledFor(TraceFlags.EwsRequest);

    // The request might need to add additional headers
    AddHeaders(request.Headers);

    // If tracing is enabled, we generate the request in-memory so that we
    // can pass it along to the ITraceListener. Then we copy the stream to
    // the request stream.
    if (needSignature || needTrace) {
      await _TraceAndEmitRequest(request, needSignature, needTrace);
    } else {
      await _EmitRequest(request);
    }

    return request;
  } on WebException catch (ex, stacktrace) {
    if (ex.Status == WebExceptionStatus.ProtocolError) {
      await _ProcessWebException(ex);
    }

    // Wrap exception if the above code block didn't throw
    throw ServiceRequestException(
      "ServiceRequestFailed(${ex.message})",
      ex,
      stacktrace,
    );
  } on IOException catch (ex, stacktrace) {
    if (request != null) {
      request.Abort();
    }
    // Wrap exception.
    throw ServiceRequestException(
      "ServiceRequestFailed($ex)",
      ex,
      stacktrace,
    );
  }
}