/* * Copyright (C) Alibaba Cloud Computing * All rights reserved. * * 版权所有 (C)阿里云计算有限公司 */ using System; using System.Collections.Generic; using System.IO; using System.Text; using Aliyun.OSS.Util; namespace Aliyun.OSS.Common.Communication { internal class ServiceRequest : ServiceMessage, IDisposable { private bool _disposed; private readonly IDictionary _parameters = new Dictionary(); /// /// Gets or sets the endpoint. /// public Uri Endpoint { get; set; } /// /// Gets or sets the resource path of the request URI. /// public String ResourcePath { get; set; } /// /// Gets or sets the HTTP method. /// public HttpMethod Method { get; set; } /// /// Gets the dictionary of the request parameters. /// public IDictionary Parameters { get { return _parameters; } } /// /// Gets whether the request can be repeated. /// public bool IsRepeatable { get { return Content == null || Content.CanSeek; } } /// /// Build the request URI from the request message. /// /// public string BuildRequestUri() { const string delimiter = "/"; var uri = Endpoint.ToString(); if (!uri.EndsWith(delimiter) && (ResourcePath == null || !ResourcePath.StartsWith(delimiter))) { uri += delimiter; } if (ResourcePath != null) uri += ResourcePath; if (IsParameterInUri()) { var paramString = HttpUtils.ConbineQueryString(_parameters); if (!string.IsNullOrEmpty(paramString)) uri += "?" + paramString; } return uri; } public Stream BuildRequestContent() { if (!IsParameterInUri()) { var paramString = HttpUtils.ConbineQueryString(_parameters); if (!string.IsNullOrEmpty(paramString)) { var buffer = Encoding.GetEncoding("utf-8").GetBytes(paramString); Stream content = new MemoryStream(); content.Write(buffer, 0, buffer.Length); content.Flush(); // Move the marker to the beginning for further read. content.Seek(0, SeekOrigin.Begin); return content; } } return Content; } private bool IsParameterInUri() { var requestHasPayload = Content != null; var requestIsPost = Method == HttpMethod.Post; var putParamsInUri = !requestIsPost || requestHasPayload; return putParamsInUri; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { if (Content != null) { Content.Close(); Content = null; } _disposed = true; } } } }