BuildEwsHttpWebRequest method

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

Implementation

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

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

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

    // The request might need to add additional headers
    this.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 this._TraceAndEmitRequest(request, needSignature, needTrace);
    } else {
      await this._EmitRequest(request);
    }

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

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