Пример #1
0
        /// <summary>
        /// add authorization
        /// </summary>
        /// <param name="qcloudSignSource">QCloudSignSource</param>
        /// <param name="request"></param>
        /// <param name="credentialProvider"></param>
        private void CheckSign(IQCloudSignSource qcloudSignSource, Request request, QCloudCredentialProvider credentialProvider)
        {
            // has authorizaiton, notice: using request.Headers, otherwise, error
            if (request.Headers.ContainsKey(CosRequestHeaderKey.AUTHORIZAIION))
            {
                QLog.Debug(TAG, "has add authorizaiton in headers");

                return;
            }

            //has no authorization, but signSourceProvider == null
            if (qcloudSignSource == null)
            {
                QLog.Debug(TAG, "signSourceProvider == null");

                return;
            }

            if (credentialProvider == null)
            {
                throw new ArgumentNullException("credentialsProvider == null");
            }

            CosXmlSigner signer = new CosXmlSigner();

            signer.Sign(request, qcloudSignSource, credentialProvider.GetQCloudCredentialsCompat(request));
        }
Пример #2
0
            public void PaserServerError(Stream inputStream, string contentType, long contentLength)
            {
                CosServerException cosServerException = new CosServerException(cosResult.httpCode, cosResult.httpMessage);
                List <string>      values;

                Headers.TryGetValue("x-cos-request-id", out values);
                cosServerException.requestId = (values != null && values.Count > 0) ? values[0] : null;
                Headers.TryGetValue("x-cos-trace-id", out values);
                cosServerException.traceId = (values != null && values.Count > 0) ? values[0] : null;

                if (inputStream != null)
                {
                    try
                    {
                        CosServerError cosServerError = XmlParse.Deserialize <CosServerError>(inputStream);

                        cosServerException.SetCosServerError(cosServerError);
                    }
                    catch (Exception ex)
                    {
                        QLog.Debug(TAG, ex.Message);
                    }
                }

                throw cosServerException;
            }
Пример #3
0
        public void AddHeader(string name, string value)
        {
            try
            {
                headers.Add(name, value);
            }
            catch (ArgumentNullException)
            {
                QLog.Debug(TAG, "AddHeader: name is null");
            }
            catch (ArgumentException)
            {
                if (String.IsNullOrEmpty(value))
                {
                    return;
                }

                if (!String.IsNullOrEmpty(headers[name]))
                {
                    headers[name] = headers[name] + ',' + value;
                }
                else
                {
                    headers[name] = value;
                }
            }
        }
Пример #4
0
            internal static void AddHeader(WebHeaderCollection webHeaderCollection, string key, string value)
            {
                if (isMonoPlatform == null)
                {
                    isMonoPlatform = monoPlatforms.Contains(Environment.OSVersion.Platform);
                }
                // HTTP headers should be encoded to iso-8859-1,
                // however it will be encoded automatically by HttpWebRequest in mono.
                if (false == isMonoPlatform)
                {
                    // Encode headers for win platforms.
                }

                if (addHeaderMethod == null)
                {
                    // Specify the internal method name for adding headers
                    // mono: AddWithoutValidate
                    // win: AddInternal
                    //var internalMethodName = (isMonoPlatform == false) ? "AddWithoutValidate" : "AddInternal";
                    var internalMethodName = "AddWithoutValidate";

                    QLog.Debug(TAG, internalMethodName.ToString());
                    var method = typeof(WebHeaderCollection).GetMethod(
                        internalMethodName,
                        BindingFlags.NonPublic | BindingFlags.Instance,
                        null,
                        new Type[] { typeof(string), typeof(string) },
                        null);

                    addHeaderMethod = method;
                }

                addHeaderMethod.Invoke(webHeaderCollection, new Object[] { key, value });
            }
Пример #5
0
        /// <summary>
        /// async to excute
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="config"></param>
        public static void Schedue(Request request, Response response, HttpClientConfig config)
        {
            HttpWebRequest httpWebRequest = null;
            RequestState   requestState   = new RequestState();

            try
            {
                requestState.request = request;

                requestState.response = response;

                httpWebRequest = WebRequest.Create(request.RequestUrlString) as HttpWebRequest;

                httpWebRequest.AllowWriteStreamBuffering = false;

                //bind webRequest
                request.BindHttpWebRequest(httpWebRequest);

                //handle request header
                HandleHttpWebRequestHeaders(request, httpWebRequest, config);

                requestState.httpWebRequest = httpWebRequest;

                //handle request body
                if (request.Body != null)
                {
                    httpWebRequest.ContentLength = request.Body.ContentLength;
                    httpWebRequest.BeginGetRequestStream(new AsyncCallback(AsyncRequestCallback), requestState);
                }
                else
                {
                    //wait for response
                    httpWebRequest.BeginGetResponse(new AsyncCallback(AsyncResponseCallback), requestState);
                }

                //print log
                PrintReqeustInfo(httpWebRequest);
            }
            catch (WebException webEx)
            {
                response.OnFinish(false, webEx);
                //abort
                requestState.Clear();
                QLog.Debug(TAG, webEx.Message, webEx);
            }
            catch (Exception ex)
            {
                response.OnFinish(false, ex);
                //abort
                requestState.Clear();
                QLog.Error(TAG, ex.Message, ex);
            }
        }
Пример #6
0
            public void Clear()
            {
                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }

                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }

                QLog.Debug(TAG, "Close");
            }
 internal void RegisterHandlerSafe(short msgType, QNetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         QLog.Error($"RegisterHandlerSafe id:{msgType} handler is null");
     }
     else
     {
         QLog.Debug($"RegisterHandlerSafe id:{msgType} handler:{handler.GetMethodName()}");
         if (!_msgHandlers.ContainsKey(msgType))
         {
             _msgHandlers.Add(msgType, handler);
         }
     }
 }
Пример #8
0
        /// <summary>
        /// print response info
        /// </summary>
        /// <param name="httpWebResponse"></param>
        private static void PrintResponseInfo(HttpWebResponse httpWebResponse)
        {
            StringBuilder responseLog = new StringBuilder("<---");

            responseLog.Append(httpWebResponse.Method).Append(' ').Append(httpWebResponse.ResponseUri.AbsoluteUri).Append('\n');
            responseLog.Append((int)httpWebResponse.StatusCode).Append(' ').Append(httpWebResponse.StatusDescription).Append('\n');
            int count = httpWebResponse.Headers.Count;

            for (int i = 0; i < count; i++)
            {
                responseLog.Append(httpWebResponse.Headers.GetKey(i)).Append(":").Append(httpWebResponse.Headers.GetValues(i)[0]).Append('\n');
            }

            responseLog.Append("<---");
            QLog.Debug(TAG, responseLog.ToString());
        }
Пример #9
0
        /// <summary>
        /// print request info
        /// </summary>
        /// <param name="httpWebRequest"></param>
        private static void PrintReqeustInfo(HttpWebRequest httpWebRequest)
        {
            StringBuilder requestLog = new StringBuilder("--->");

            requestLog.Append(httpWebRequest.Method).Append(' ').Append(httpWebRequest.Address.AbsoluteUri).Append('\n');
            int count = httpWebRequest.Headers.Count;

            for (int i = 0; i < count; i++)
            {
                requestLog.Append(httpWebRequest.Headers.GetKey(i)).Append(":").Append(httpWebRequest.Headers.GetValues(i)[0]).Append('\n');
            }

            requestLog.Append("allow auto redirect: " + httpWebRequest.AllowAutoRedirect).Append('\n');
            requestLog.Append("connect timeout: " + httpWebRequest.Timeout).Append('\n');
            requestLog.Append("read write timeout: " + httpWebRequest.ReadWriteTimeout).Append('\n');
            requestLog.Append("AllowWriteStreamBuffering: " + httpWebRequest.AllowWriteStreamBuffering).Append('\n');
            //requestLog.Append("proxy: " + (httpWebRequest.Proxy == null ? "null" : ((WebProxy)httpWebRequest.Proxy).Address.ToString()));
            requestLog.Append("<---");
            QLog.Debug(TAG, requestLog.ToString());
        }
 public void RegisterHandler(short msgType, QNetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         QLog.Error($"RegisterHandler id:{msgType} handler is null");
     }
     else if (msgType <= 31)
     {
         QLog.Error($"RegisterHandler: Cannot replace system message handler {msgType}");
     }
     else
     {
         if (_msgHandlers.ContainsKey(msgType))
         {
             QLog.Log($"RegisterHandler replacing {msgType}");
             _msgHandlers.Remove(msgType);
         }
         QLog.Debug($"RegisterHandler id:{msgType} handler:{handler.GetMethodName()}");
         _msgHandlers.Add(msgType, handler);
     }
 }
Пример #11
0
 public override void Refresh()
 {
     //TODO update value
     QLog.Debug("DefaultQCloudCredentialProvider", "need to update QCloudCredentials");
     //invoke SetSetQCloudCredential(string secretId, string secretKey, string keyTime)
 }
Пример #12
0
        /// <summary>
        /// sync excute
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static void Excute(Request request, Response response, HttpClientConfig config)
        {
            HttpWebRequest  httpWebRequest  = null;
            HttpWebResponse httpWebResponse = null;

            try
            {
                //step1: create HttpWebRequest by request.url
                httpWebRequest = HttpWebRequest.Create(request.RequestUrlString) as HttpWebRequest;

                httpWebRequest.AllowWriteStreamBuffering = false;

                //bind webRequest
                request.BindHttpWebRequest(httpWebRequest);

                // handler request
                HandleHttpWebRequest(httpWebRequest, request, config);

                //final: get response
                httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;

                //notify has been got response
                request.onNotifyGetResponse();

                //handle response for [100, 300)
                HandleHttpWebResponse(httpWebResponse, response);
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null && webEx.Response is HttpWebResponse)
                {
                    //notify has been got response

                    request.onNotifyGetResponse();

                    httpWebResponse = (HttpWebResponse)webEx.Response;
                    //handle response for [400, 500]
                    HandleHttpWebResponse(httpWebResponse, response);
                }
                else
                {
                    //QLog.E(TAG, webEx.Message, webEx);
                    throw;
                }
            }
            catch (Exception)
            {
                //QLog.E(TAG, ex.Message, ex);
                throw;
            }
            finally
            {
                if (httpWebResponse != null)
                {
                    // print log
                    PrintResponseInfo(httpWebResponse);
                    httpWebResponse.Close();
                    //QLog.D("XIAO", "response close");
                }

                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                    //QLog.D("XIAO", "request close");
                }

                QLog.Debug(TAG, "close");
            }
        }