コード例 #1
0
        /// <summary>
        /// 发送异步请求,并获取处理回复
        /// </summary>
        /// <param name="asyncResult">异步状态</param>
        private void firePostDataRequest(IAsyncResult asyncResult)
        {
            this.startTime = DateTime.Now;
            HttpWebRequest request        = (HttpWebRequest)asyncResult.AsyncState;
            Stream         postDataStream = request.EndGetRequestStream(asyncResult);

            int totalBytes   = this.PostArgs.Data.Length;
            int writeTimes   = totalBytes / BUFFER_SIZE;
            int bytesWritten = 0;

            if (totalBytes % BUFFER_SIZE != 0)
            {
                writeTimes += 1;
            }
            for (int i = 0; i < writeTimes; i++)
            {
                //检查取消信号
                if (CancellationSignal != null && CancellationSignal())
                {
                    if (CompletionHandler != null)
                    {
                        CompletionHandler(ResponseInfo.cancelled(), "");
                    }
                    postDataStream.Close();
                    return;
                }
                int offset = i * BUFFER_SIZE;
                int size   = BUFFER_SIZE;
                if (i == writeTimes - 1)
                {
                    size = totalBytes - i * BUFFER_SIZE;
                }
                postDataStream.Write(this.PostArgs.Data, offset, size);
                bytesWritten += size;
                //请求进度处理
                if (ProgressHandler != null)
                {
                    ProgressHandler(bytesWritten, totalBytes);
                }
            }
            postDataStream.Flush();
            postDataStream.Close();
            request.BeginGetResponse(new AsyncCallback(handleResponse), request);
        }
コード例 #2
0
        /// <summary>
        /// 发送异步请求,并获取处理回复
        /// </summary>
        /// <param name="asyncResult">异步状态</param>
        private void fireMultipartPostRequest(IAsyncResult asyncResult)
        {
            this.startTime = DateTime.Now;
            HttpWebRequest request        = (HttpWebRequest)asyncResult.AsyncState;
            Stream         postDataStream = request.EndGetRequestStream(asyncResult);

            int bytesWritten = 0;
            int totalBytes   = (int)postDataMemoryStream.Length;
            int writeTimes   = totalBytes / BUFFER_SIZE;

            if (totalBytes % BUFFER_SIZE != 0)
            {
                writeTimes += 1;
            }
            postDataMemoryStream.Seek(0, SeekOrigin.Begin);
            int memNumRead = 0;

            byte[] memBuffer = new byte[BUFFER_SIZE];
            while ((memNumRead = postDataMemoryStream.Read(memBuffer, 0, memBuffer.Length)) != 0)
            {
                //检查取消信号
                if (this.CancellationSignal != null && this.CancellationSignal())
                {
                    if (this.CompletionHandler != null)
                    {
                        this.CompletionHandler(ResponseInfo.cancelled(), "");
                    }
                    postDataStream.Close();
                    return;
                }
                postDataStream.Write(memBuffer, 0, memNumRead);
                bytesWritten += memNumRead;
                //处理进度
                if (ProgressHandler != null)
                {
                    ProgressHandler(bytesWritten, totalBytes);
                }
            }
            postDataMemoryStream.Close();
            postDataStream.Flush();
            postDataStream.Close();
            request.BeginGetResponse(new AsyncCallback(handleResponse), request);
        }
コード例 #3
0
ファイル: SimpleUpload.cs プロジェクト: qiniu/csharp-sdk
 private static void OnUploadCompleted(string key, ResponseInfo respInfo, string respJson)
 {
     // respInfo.StatusCode
     // respJson是返回的json消息,示例: { "key":"FILE","hash":"HASH","fsize":FILE_SIZE }
 }
コード例 #4
0
ファイル: HttpManager.cs プロジェクト: qiniu/csharp-sdk
        private void handleWebResponse(HttpWebResponse pWebResp, CompletionHandler pCompletionHandler)
        {
            DateTime startTime = DateTime.Now;
            //check for exception
            int statusCode = ResponseInfo.NetworkError;
            string reqId = null;
            string xlog = null;
            string ip = null;
            string xvia = null;
            string error = null;
            string host = null;
            string respData = null;
            int contentLength = -1;

            if (pWebResp != null)
            {
                statusCode = (int)pWebResp.StatusCode;

                if (pWebResp.Headers != null)
                {
                    WebHeaderCollection respHeaders = pWebResp.Headers;
                    foreach (string headerName in respHeaders.AllKeys)
                    {
                        if (headerName.Equals("X-Reqid"))
                        {
                            reqId = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Log"))
                        {
                            xlog = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Px"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Fw-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Host"))
                        {
                            host = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Content-Length"))
                        {
                            contentLength = int.Parse(respHeaders[headerName].ToString());
                        }
                    }
                }

                if (contentLength > 0)
                {
                    Stream ps = pWebResp.GetResponseStream();
                    byte[] raw = new byte[contentLength];
                    int bytesRead = 0; // 已读取的字节数
                    int bytesLeft = contentLength; // 剩余字节数
                    while (bytesLeft > 0)
                    {
                        bytesRead = ps.Read(raw, contentLength - bytesLeft, bytesLeft);
                        bytesLeft -= bytesRead;
                    }

                    respData = Encoding.UTF8.GetString(raw);

                    try
                    {
                        /////////////////////////////////////////////////////////////
                        // 改进Response的error解析, 根据HttpStatusCode
                        // @fengyh 2016-08-17 18:29
                        /////////////////////////////////////////////////////////////
                        if (statusCode != (int)HCODE.OK)
                        {
                            bool isOtherCode = HttpCode.GetErrorMessage(statusCode, out error);

                            if (isOtherCode)
                            {
                                Dictionary<string, string> errorDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(respData);
                                error = errorDict["error"];
                            }
                        }
                    }
                    catch (Exception) { }
                }
                else
                {
                    //statusCode = -1;
                    //error = "response err";
                }
            }
            else
            {
                error = "invalid response";
                statusCode = -1;
            }

            double duration = DateTime.Now.Subtract(startTime).TotalSeconds;
            ResponseInfo respInfo = new ResponseInfo(statusCode, reqId, xlog, xvia, host, ip, duration, error);
            if (pCompletionHandler != null)
            {
                pCompletionHandler(respInfo, respData);
            }
        }
コード例 #5
0
ファイル: HttpManager.cs プロジェクト: atangzhxt/csharp-sdk
        private void handleErrorWebResponse(HttpWebResponse pWebResp, CompletionHandler pCompletionHandler, Exception pExp)
        {
            DateTime startTime  = DateTime.Now;
            int      statusCode = ResponseInfo.NetworkError;
            //parse self defined code from the error message
            string expMsg     = pExp.Message;
            int    indexStart = expMsg.IndexOf("(");

            if (indexStart != -1)
            {
                int indexEnd = expMsg.IndexOf(")", indexStart);
                if (indexStart != -1 && indexEnd != -1)
                {
                    string statusCodeStr = expMsg.Substring(indexStart + 1, indexEnd - indexStart - 1);
                    try
                    {
                        statusCode = Convert.ToInt32(statusCodeStr);
                    }
                    catch (Exception) { }
                }
            }
            //check for exception
            string reqId    = null;
            string xlog     = null;
            string ip       = null;
            string xvia     = null;
            string error    = null;
            string host     = null;
            string respData = null;

            if (pWebResp != null && pWebResp.Headers != null)
            {
                WebHeaderCollection respHeaders = pWebResp.Headers;
                foreach (string headerName in respHeaders.AllKeys)
                {
                    if (headerName.Equals("X-Reqid"))
                    {
                        reqId = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("X-Log"))
                    {
                        xlog = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("X-Via"))
                    {
                        xvia = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("X-Px"))
                    {
                        xvia = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("Fw-Via"))
                    {
                        xvia = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("Host"))
                    {
                        host = respHeaders[headerName].ToString();
                    }
                }

                using (StreamReader respStream = new StreamReader(pWebResp.GetResponseStream()))
                {
                    respData = respStream.ReadToEnd();
                }

                try
                {
                    /////////////////////////////////////////////////////////////
                    // 改进Response的error解析, 根据HttpStatusCode
                    // @fengyh 2016-08-17 18:29
                    /////////////////////////////////////////////////////////////
                    if (statusCode != (int)HCODE.OK)
                    {
                        bool isOtherCode = HttpCode.GetErrorMessage(statusCode, out error);

                        if (isOtherCode)
                        {
                            Dictionary <string, string> errorDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(respData);
                            error = errorDict["error"];
                        }
                    }
                }
                catch (Exception) { }
            }
            else
            {
                error = pExp.Message;
            }

            double       duration = DateTime.Now.Subtract(startTime).TotalSeconds;
            ResponseInfo respInfo = new ResponseInfo(statusCode, reqId, xlog, xvia, host, ip, duration, error);

            if (pCompletionHandler != null)
            {
                pCompletionHandler(respInfo, respData);
            }
        }
コード例 #6
0
ファイル: HttpManager.cs プロジェクト: atangzhxt/csharp-sdk
        private void handleWebResponse(HttpWebResponse pWebResp, CompletionHandler pCompletionHandler)
        {
            DateTime startTime = DateTime.Now;
            //check for exception
            int    statusCode = ResponseInfo.NetworkError;
            string reqId      = null;
            string xlog       = null;
            string ip         = null;
            string xvia       = null;
            string error      = null;
            string host       = null;
            string respData   = null;

            statusCode = (int)pWebResp.StatusCode;
            if (pWebResp.Headers != null)
            {
                WebHeaderCollection respHeaders = pWebResp.Headers;
                foreach (string headerName in respHeaders.AllKeys)
                {
                    if (headerName.Equals("X-Reqid"))
                    {
                        reqId = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("X-Log"))
                    {
                        xlog = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("X-Via"))
                    {
                        xvia = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("X-Px"))
                    {
                        xvia = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("Fw-Via"))
                    {
                        xvia = respHeaders[headerName].ToString();
                    }
                    else if (headerName.Equals("Host"))
                    {
                        host = respHeaders[headerName].ToString();
                    }
                }

                using (StreamReader respStream = new StreamReader(pWebResp.GetResponseStream()))
                {
                    respData = respStream.ReadToEnd();
                }

                try
                {
                    /////////////////////////////////////////////////////////////
                    // 改进Response的error解析, 根据HttpStatusCode
                    // @fengyh 2016-08-17 18:29
                    /////////////////////////////////////////////////////////////
                    if (statusCode != (int)HCODE.OK)
                    {
                        bool isOtherCode = HttpCode.GetErrorMessage(statusCode, out error);

                        if (isOtherCode)
                        {
                            Dictionary <string, string> errorDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(respData);
                            error = errorDict["error"];
                        }
                    }
                }
                catch (Exception) { }
            }

            double       duration = DateTime.Now.Subtract(startTime).TotalSeconds;
            ResponseInfo respInfo = new ResponseInfo(statusCode, reqId, xlog, xvia, host, ip, duration, error);

            if (pCompletionHandler != null)
            {
                pCompletionHandler(respInfo, respData);
            }
        }
コード例 #7
0
ファイル: HttpManager.cs プロジェクト: atangzhxt/csharp-sdk
        /// <summary>
        /// post multi-part data form to remote server
        /// used to upload file
        /// </summary>
        /// <param name="pUrl"></param>
        /// <param name="pHeaders"></param>
        /// <param name="pPostParams"></param>
        /// <param name="httpFormFile"></param>
        /// <param name="pProgressHandler"></param>
        /// <param name="pCompletionHandler"></param>
        public void postMultipartDataForm(string pUrl, Dictionary <string, string> pHeaders,
                                          Dictionary <string, string> pPostParams, HttpFormFile pFormFile,
                                          ProgressHandler pProgressHandler, CompletionHandler pCompletionHandler)
        {
            if (pFormFile == null)
            {
                if (pCompletionHandler != null)
                {
                    pCompletionHandler(ResponseInfo.fileError(new Exception("no file specified")), "");
                }
                return;
            }

            HttpWebRequest  vWebReq  = null;
            HttpWebResponse vWebResp = null;

            try
            {
                vWebReq = (HttpWebRequest)WebRequest.Create(pUrl);
                vWebReq.ServicePoint.Expect100Continue = false;
            }
            catch (Exception ex)
            {
                if (pCompletionHandler != null)
                {
                    pCompletionHandler(ResponseInfo.invalidRequest(ex.Message), "");
                }
                return;
            }

            try
            {
                vWebReq.UserAgent         = this.getUserAgent();
                vWebReq.AllowAutoRedirect = false;
                vWebReq.Method            = "POST";

                //create boundary
                string formBoundaryStr = this.createFormDataBoundary();
                string contentType     = string.Format("multipart/form-data; boundary={0}", formBoundaryStr);
                vWebReq.ContentType = contentType;
                if (pHeaders != null)
                {
                    foreach (KeyValuePair <string, string> kvp in pHeaders)
                    {
                        if (!kvp.Key.Equals("Content-Type"))
                        {
                            vWebReq.Headers.Add(kvp.Key, kvp.Value);
                        }
                    }
                }

                //write post body
                vWebReq.AllowWriteStreamBuffering = true;

                byte[] formBoundaryBytes = Encoding.UTF8.GetBytes(string.Format("{0}{1}\r\n",
                                                                                FORM_BOUNDARY_TAG, formBoundaryStr));
                byte[] formBoundaryEndBytes = Encoding.UTF8.GetBytes(string.Format("\r\n{0}{1}{2}\r\n",
                                                                                   FORM_BOUNDARY_TAG, formBoundaryStr, FORM_BOUNDARY_TAG));

                using (Stream vWebReqStream = vWebReq.GetRequestStream())
                {
                    //write params
                    if (pPostParams != null)
                    {
                        foreach (KeyValuePair <string, string> kvp in pPostParams)
                        {
                            vWebReqStream.Write(formBoundaryBytes, 0, formBoundaryBytes.Length);

                            byte[] formPartTitleData = Encoding.UTF8.GetBytes(
                                string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n", kvp.Key));
                            vWebReqStream.Write(formPartTitleData, 0, formPartTitleData.Length);

                            byte[] formPartBodyData = Encoding.UTF8.GetBytes(string.Format("\r\n{0}\r\n", kvp.Value));
                            vWebReqStream.Write(formPartBodyData, 0, formPartBodyData.Length);
                        }
                    }

                    vWebReqStream.Write(formBoundaryBytes, 0, formBoundaryBytes.Length);

                    //write file name
                    string filename = pFormFile.Filename;
                    if (string.IsNullOrEmpty(filename))
                    {
                        filename = this.createRandomFilename();
                    }
                    byte[] filePartTitleData = Encoding.UTF8.GetBytes(
                        string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", filename));
                    vWebReqStream.Write(filePartTitleData, 0, filePartTitleData.Length);
                    //write content type
                    string mimeType = FORM_MIME_OCTECT;  //!!!注意这里 @fengyh 2016-08-17 15:00
                    if (!string.IsNullOrEmpty(pFormFile.ContentType))
                    {
                        mimeType = pFormFile.ContentType;
                    }
                    byte[] filePartMimeData = Encoding.UTF8.GetBytes(string.Format("Content-Type: {0}\r\n\r\n", mimeType));
                    vWebReqStream.Write(filePartMimeData, 0, filePartMimeData.Length);

                    //write file data
                    switch (pFormFile.BodyType)
                    {
                    case HttpFileType.FILE_PATH:
                        try
                        {
                            FileStream fs = File.Open(pFormFile.BodyFile, FileMode.Open, FileAccess.Read);
                            this.writeHttpRequestBody(fs, vWebReqStream);
                        }
                        catch (Exception fex)
                        {
                            if (pCompletionHandler != null)
                            {
                                pCompletionHandler(ResponseInfo.fileError(fex), "");
                            }
                        }
                        break;

                    case HttpFileType.FILE_STREAM:
                        this.writeHttpRequestBody(pFormFile.BodyStream, vWebReqStream);
                        break;

                    case HttpFileType.DATA_BYTES:
                        vWebReqStream.Write(pFormFile.BodyBytes, 0, pFormFile.BodyBytes.Length);
                        break;

                    case HttpFileType.DATA_SLICE:
                        vWebReqStream.Write(pFormFile.BodyBytes, pFormFile.Offset, pFormFile.Count);
                        break;
                    }

                    vWebReqStream.Write(formBoundaryEndBytes, 0, formBoundaryEndBytes.Length);
                    vWebReqStream.Flush();
                }

                //fire request
                vWebResp = (HttpWebResponse)vWebReq.GetResponse();
                handleWebResponse(vWebResp, pCompletionHandler);
            }
            catch (WebException wexp)
            {
                // FIX-HTTP 4xx/5xx Error 2016-11-22, 17:00 @fengyh
                HttpWebResponse xWebResp = wexp.Response as HttpWebResponse;
                handleErrorWebResponse(xWebResp, pCompletionHandler, wexp);
            }
            catch (Exception exp)
            {
                handleErrorWebResponse(vWebResp, pCompletionHandler, exp);
            }
        }
コード例 #8
0
ファイル: HttpManager.cs プロジェクト: atangzhxt/csharp-sdk
        /// <summary>
        /// post binary data to remote server
        /// </summary>
        /// <param name="pUrl"></param>
        /// <param name="pHeaders"></param>
        /// <param name="pPostData"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <param name="pCompletionHandler"></param>
        public void postData(string pUrl, Dictionary <string, string> pHeaders,
                             byte[] pPostData, int offset, int count, string contentType,
                             CompletionHandler pCompletionHandler)
        {
            HttpWebRequest  vWebReq  = null;
            HttpWebResponse vWebResp = null;

            try
            {
                vWebReq = (HttpWebRequest)WebRequest.Create(pUrl);
            }
            catch (Exception ex)
            {
                if (pCompletionHandler != null)
                {
                    pCompletionHandler(ResponseInfo.invalidRequest(ex.Message), "");
                }
                return;
            }

            try
            {
                vWebReq.UserAgent         = this.getUserAgent();
                vWebReq.AllowAutoRedirect = false;
                vWebReq.Method            = "POST";
                if (!string.IsNullOrEmpty(contentType))
                {
                    vWebReq.ContentType = contentType;
                }
                else
                {
                    vWebReq.ContentType = FORM_MIME_OCTECT;
                }
                if (pHeaders != null)
                {
                    foreach (KeyValuePair <string, string> kvp in pHeaders)
                    {
                        if (!kvp.Key.Equals("Content-Type"))
                        {
                            vWebReq.Headers.Add(kvp.Key, kvp.Value);
                        }
                    }
                }

                vWebReq.AllowWriteStreamBuffering = true;
                // write data
                using (Stream vWebReqStream = vWebReq.GetRequestStream())
                {
                    vWebReqStream.Write(pPostData, offset, count);
                    vWebReqStream.Flush();
                }

                //fire request
                vWebResp = (HttpWebResponse)vWebReq.GetResponse();
                handleWebResponse(vWebResp, pCompletionHandler);
            }
            catch (WebException wexp)
            {
                // FIX-HTTP 4xx/5xx Error 2016-11-22, 17:00 @fengyh
                HttpWebResponse xWebResp = wexp.Response as HttpWebResponse;
                handleErrorWebResponse(xWebResp, pCompletionHandler, wexp);
            }
            catch (Exception exp)
            {
                handleErrorWebResponse(vWebResp, pCompletionHandler, exp);
            }
        }
コード例 #9
0
ファイル: HttpManager.cs プロジェクト: atangzhxt/csharp-sdk
        /// <summary>
        /// post the url encoded form to remote server
        /// </summary>
        /// <param name="pUrl"></param>
        /// <param name="pHeaders"></param>
        /// <param name="pParamDict"></param>
        /// <param name="pCompletionHandler"></param>
        public void postForm(string pUrl, Dictionary <string, string> pHeaders,
                             Dictionary <string, string[]> pPostParams, CompletionHandler pCompletionHandler)
        {
            HttpWebRequest  vWebReq  = null;
            HttpWebResponse vWebResp = null;

            try
            {
                vWebReq = (HttpWebRequest)WebRequest.Create(pUrl);
            }
            catch (Exception ex)
            {
                if (pCompletionHandler != null)
                {
                    pCompletionHandler(ResponseInfo.invalidRequest(ex.Message), "");
                }
                return;
            }

            try
            {
                vWebReq.UserAgent         = this.getUserAgent();
                vWebReq.AllowAutoRedirect = false;
                vWebReq.Method            = "POST";
                vWebReq.ContentType       = FORM_MIME_URLENCODED;
                if (pHeaders != null)
                {
                    foreach (KeyValuePair <string, string> kvp in pHeaders)
                    {
                        if (!kvp.Key.Equals("Content-Type"))
                        {
                            vWebReq.Headers.Add(kvp.Key, kvp.Value);
                        }
                    }
                }

                // format the post body
                StringBuilder vPostBody = new StringBuilder();
                if (pPostParams != null)
                {
                    foreach (KeyValuePair <string, string[]> kvp in pPostParams)
                    {
                        foreach (string vVal in kvp.Value)
                        {
                            vPostBody.AppendFormat("{0}={1}&",
                                                   Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(vVal));
                        }
                    }
                    // write data
                    vWebReq.AllowWriteStreamBuffering = true;
                    using (Stream vWebReqStream = vWebReq.GetRequestStream())
                    {
                        vWebReqStream.Write(Encoding.UTF8.GetBytes(vPostBody.ToString()),
                                            0, vPostBody.Length - 1);
                        vWebReqStream.Flush();
                    }
                }

                //fire request
                vWebResp = (HttpWebResponse)vWebReq.GetResponse();
                handleWebResponse(vWebResp, pCompletionHandler);
            }
            catch (WebException wexp)
            {
                // FIX-HTTP 4xx/5xx Error 2016-11-22, 17:00 @fengyh
                HttpWebResponse xWebResp = wexp.Response as HttpWebResponse;
                handleErrorWebResponse(xWebResp, pCompletionHandler, wexp);
            }
            catch (Exception exp)
            {
                handleErrorWebResponse(vWebResp, pCompletionHandler, exp);
            }
        }
コード例 #10
0
ファイル: UploadManager.cs プロジェクト: qiniu/csharp-sdk
 private void DefaultUpCompletionHandler(string key,ResponseInfo respInfo,string respJson)
 {
     Console.WriteLine(string.Format("key={0}\nrespInfo={1}\nresponse={2}", key, respInfo, respJson));
 }
コード例 #11
0
ファイル: HttpManager.cs プロジェクト: bleupierre/wp-sdk
        /// <summary>
        /// 处理Http请求结果
        /// </summary>
        /// <param name="asyncResult">异步状态</param>
        private void handleResponse(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            //check for exception
            int statusCode = ResponseInfo.NetworkError;
            string reqId = null;
            string xlog = null;
            string ip = null;
            string xvia = null;
            string error = null;
            string host = null;
            string respData = null;
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    response = (HttpWebResponse)wex.Response;
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            if (response != null)
            {
                statusCode = (int)response.StatusCode;
                if (response.Headers != null)
                {
                    WebHeaderCollection respHeaders = response.Headers;
                    foreach (string headerName in respHeaders.AllKeys)
                    {
                        if (headerName.Equals("X-Reqid"))
                        {
                            reqId = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Log"))
                        {
                            xlog = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Px"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Fw-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Host"))
                        {
                            host = respHeaders[headerName].ToString();
                        }
                    }
                    using (StreamReader respStream = new StreamReader(response.GetResponseStream()))
                    {
                        respData = respStream.ReadToEnd();
                        if (respData != null)
                        {
                            try
                            {
                                Dictionary<string, string> respErrorDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(respData);
                                if (respErrorDict != null && respErrorDict.ContainsKey("error"))
                                {
                                    error = respErrorDict["error"];
                                }
                            }
                            catch (Exception)
                            {
                                error = respData;
                            }
                        }
                        else
                        {
                            error = "no response";
                        }

                    }
                    ip = webRequest.RequestUri.Authority;
                    response.Close();
                }
            }

            duration = DateTime.Now.Subtract(this.startTime).TotalSeconds;
            ResponseInfo respInfo = new ResponseInfo(statusCode, reqId, xlog, xvia, host, ip, duration, error);
            if (this.CompletionHandler != null)
            {
                this.CompletionHandler(respInfo, respData);
            }
            allDone.Set();
        }
コード例 #12
0
        /// <summary>
        /// 处理Http请求结果
        /// </summary>
        /// <param name="asyncResult">异步状态</param>
        private void handleResponse(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            //check for exception
            int             statusCode = ResponseInfo.NetworkError;
            string          reqId      = null;
            string          xlog       = null;
            string          ip         = null;
            string          xvia       = null;
            string          error      = null;
            string          host       = null;
            string          respData   = null;
            HttpWebResponse response   = null;

            try
            {
                response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    response = (HttpWebResponse)wex.Response;
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            if (response != null)
            {
                statusCode = (int)response.StatusCode;
                if (response.Headers != null)
                {
                    WebHeaderCollection respHeaders = response.Headers;
                    foreach (string headerName in respHeaders.AllKeys)
                    {
                        if (headerName.Equals("X-Reqid"))
                        {
                            reqId = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Log"))
                        {
                            xlog = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Px"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Fw-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Host"))
                        {
                            host = respHeaders[headerName].ToString();
                        }
                    }
                    using (StreamReader respStream = new StreamReader(response.GetResponseStream()))
                    {
                        respData = respStream.ReadToEnd();
                        if (respData != null)
                        {
                            try
                            {
                                Dictionary <string, string> respErrorDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(respData);
                                if (respErrorDict != null && respErrorDict.ContainsKey("error"))
                                {
                                    error = respErrorDict["error"];
                                }
                            }
                            catch (Exception)
                            {
                                error = respData;
                            }
                        }
                        else
                        {
                            error = "no response";
                        }
                    }
                    ip = webRequest.RequestUri.Authority;
                    response.Close();
                }
            }

            duration = DateTime.Now.Subtract(this.startTime).TotalSeconds;
            ResponseInfo respInfo = new ResponseInfo(statusCode, reqId, xlog, xvia, host, ip, duration, error);

            if (this.CompletionHandler != null)
            {
                this.CompletionHandler(respInfo, respData);
            }
            allDone.Set();
        }
コード例 #13
0
        /// <summary>
        /// 发送格式为multipart/form-data的POST请求
        /// </summary>
        /// <param name="url">请求Url</param>
        public void multipartPost(string url)
        {
            this.webRequest                   = (HttpWebRequest)WebRequest.CreateHttp(url);
            this.webRequest.UserAgent         = this.getUserAgent();
            this.webRequest.AllowAutoRedirect = false;
            this.webRequest.Method            = "POST";
            this.webRequest.ContentType       = string.Format("{0}; boundary={1}", APPLICATION_MULTIPART_FORM, MULTIPART_BOUNDARY);
            //准备数据
            this.postDataMemoryStream = new MemoryStream();
            byte[] boundarySepTag       = Encoding.UTF8.GetBytes(MULTIPART_BOUNDARY_SEP_TAG);
            byte[] boundaryData         = Encoding.UTF8.GetBytes(MULTIPART_BOUNDARY);
            byte[] multiPartSepLineData = Encoding.UTF8.GetBytes(MULTIPART_SEP_LINE);
            //写入参数
            if (this.PostArgs != null && this.PostArgs.Params != null)
            {
                foreach (KeyValuePair <string, string> kvp in this.PostArgs.Params)
                {
                    //写入boundary起始标记
                    postDataMemoryStream.Write(boundarySepTag, 0, boundarySepTag.Length);
                    //写入boundary
                    postDataMemoryStream.Write(boundaryData, 0, boundaryData.Length);
                    //写入头部和数据
                    postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
                    byte[] contentHeaderData = Encoding.UTF8.GetBytes(
                        string.Format("Content-Disposition: form-data; name=\"{0}\"", kvp.Key));
                    postDataMemoryStream.Write(contentHeaderData, 0, contentHeaderData.Length);
                    postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
                    postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
                    byte[] contentData = Encoding.UTF8.GetBytes(kvp.Value);
                    postDataMemoryStream.Write(contentData, 0, contentData.Length);
                    postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
                }
            }
            //写入文件名词和MimeType
            postDataMemoryStream.Write(boundarySepTag, 0, boundarySepTag.Length);
            postDataMemoryStream.Write(boundaryData, 0, boundaryData.Length);
            postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
            string fileName = this.PostArgs.FileName;

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = string.Format("RandomFileName_{0}", genId());
            }
            byte[] fileHeaderData = Encoding.UTF8.GetBytes(
                string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", fileName));
            string fileContentType = "application/octet-stream";

            if (!string.IsNullOrEmpty(this.PostArgs.MimeType))
            {
                fileContentType = this.PostArgs.MimeType;
            }
            byte[] fileContentTypeData = Encoding.UTF8.GetBytes(string.Format("Content-Type: {0}", fileContentType));
            postDataMemoryStream.Write(fileHeaderData, 0, fileHeaderData.Length);
            postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
            postDataMemoryStream.Write(fileContentTypeData, 0, fileContentTypeData.Length);
            postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
            postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
            //写入文件数据
            if (FileContentType == PostContentType.BYTES)
            {
                postDataMemoryStream.Write(this.PostArgs.Data, 0, this.PostArgs.Data.Length);
            }
            else if (FileContentType == PostContentType.FILE)
            {
                try
                {
                    using (FileStream fs = IsolatedStorageFile.GetUserStoreForApplication()
                                           .OpenFile(this.PostArgs.File, FileMode.Open, FileAccess.Read))
                    {
                        byte[] buffer  = new byte[BUFFER_SIZE];
                        int    numRead = -1;
                        while ((numRead = fs.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            postDataMemoryStream.Write(buffer, 0, numRead);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (this.CompletionHandler != null)
                    {
                        this.CompletionHandler(ResponseInfo.fileError(ex), "");
                    }
                    return;
                }
            }
            else if (FileContentType == PostContentType.STREAM)
            {
                try
                {
                    byte[] buffer  = new byte[BUFFER_SIZE];
                    int    numRead = -1;
                    while ((numRead = this.PostArgs.Stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        postDataMemoryStream.Write(buffer, 0, numRead);
                    }
                }
                catch (Exception ex)
                {
                    if (this.CompletionHandler != null)
                    {
                        this.CompletionHandler(ResponseInfo.fileError(ex), "");
                    }
                    return;
                }
            }
            postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
            //写入boundary结束标记
            postDataMemoryStream.Write(boundarySepTag, 0, boundarySepTag.Length);
            postDataMemoryStream.Write(boundaryData, 0, boundaryData.Length);
            postDataMemoryStream.Write(boundarySepTag, 0, boundarySepTag.Length);
            postDataMemoryStream.Write(multiPartSepLineData, 0, multiPartSepLineData.Length);
            postDataMemoryStream.Flush();
            //设置ContentLength
            this.webRequest.ContentLength = postDataMemoryStream.Length;
            if (this.webRequest.Headers == null)
            {
                this.webRequest.Headers = new WebHeaderCollection();
            }
            foreach (string headerKey in this.Headers.AllKeys)
            {
                this.webRequest.Headers[headerKey] = this.Headers[headerKey];
            }
            this.webRequest.BeginGetRequestStream(new AsyncCallback(fireMultipartPostRequest), webRequest);
            allDone.WaitOne(timeout);
        }
コード例 #14
0
        private void handleWebResponse(HttpWebResponse pWebResp, CompletionHandler pCompletionHandler)
        {
            DateTime startTime = DateTime.Now;
            //check for exception
            int    statusCode    = ResponseInfo.NetworkError;
            string reqId         = null;
            string xlog          = null;
            string ip            = null;
            string xvia          = null;
            string error         = null;
            string host          = null;
            string respData      = null;
            int    contentLength = -1;
            bool   recvInvalid   = false;

            if (pWebResp != null)
            {
                statusCode = (int)pWebResp.StatusCode;

                if (pWebResp.Headers != null)
                {
                    WebHeaderCollection respHeaders = pWebResp.Headers;
                    foreach (string headerName in respHeaders.AllKeys)
                    {
                        if (headerName.Equals("X-Reqid"))
                        {
                            reqId = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Log"))
                        {
                            xlog = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("X-Px"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Fw-Via"))
                        {
                            xvia = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Host"))
                        {
                            host = respHeaders[headerName].ToString();
                        }
                        else if (headerName.Equals("Content-Length"))
                        {
                            contentLength = int.Parse(respHeaders[headerName].ToString());
                        }
                    }
                }

                using (StreamReader respStream = new StreamReader(pWebResp.GetResponseStream()))
                {
                    respData = respStream.ReadToEnd();

                    if (contentLength > 0)
                    {
                        if (respData.Length != contentLength)
                        {
                            recvInvalid = true;
                        }
                    }
                }

                try
                {
                    /////////////////////////////////////////////////////////////
                    // 改进Response的error解析, 根据HttpStatusCode
                    // @fengyh 2016-08-17 18:29
                    /////////////////////////////////////////////////////////////
                    if (statusCode != (int)HCODE.OK)
                    {
                        bool isOtherCode = HttpCode.GetErrorMessage(statusCode, out error);

                        if (isOtherCode)
                        {
                            Dictionary <string, string> errorDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(respData);
                            error = errorDict["error"];
                        }
                    }
                }
                catch (Exception) { }

                if (recvInvalid)
                {
                    statusCode = -1;
                    string err = string.Format("response-recv is not complete RECV={0},TOTAL={1} {2}", respData.Length, contentLength, error);
                    Console.WriteLine(err);
                    error = err;
                }

                pWebResp.Close();
            }
            else
            {
                error      = "invalid response";
                statusCode = -1;
            }

            double       duration = DateTime.Now.Subtract(startTime).TotalSeconds;
            ResponseInfo respInfo = new ResponseInfo(statusCode, reqId, xlog, xvia, host, ip, duration, error);

            if (pCompletionHandler != null)
            {
                pCompletionHandler(respInfo, respData);
            }
        }