const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout

    #endregion Fields

    #region Methods

    public static String GetResponseBody(HttpWebResponse response)
    {
        Stream responseStream = response.GetResponseStream();
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStreamReader = new StreamReader(responseStream,enc);
        return responseStreamReader.ReadToEnd();
    }
    private static Boolean getResponse(HttpWebRequest request)
    {
        try
        {
            response = request.GetResponse() as HttpWebResponse;
            return true;
        }
        catch (WebException e)
        {
            Console.WriteLine("Exception Message :" + e.Message);
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                var response = ((HttpWebResponse)e.Response);
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                var text = reader.ReadToEnd();
                Console.WriteLine("Response Description : {0}", text);

            }
            return false;
        }
    }
Exemple #3
0
        /// <inheritdoc/>
        public async Task <byte[]> ReadAsByteArrayAsync()
        {
            using (Stream stream = _response?.GetResponseStream() ?? throw new InvalidOperationException("There is no content to read."))
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    await stream.CopyToAsync(memStream, int.MaxValue).ConfigureAwait(false);

                    return(memStream.ToArray());
                }
            }
        }
Exemple #4
0
    public static void HandleResponse(HttpWebResponse response)
    {
        // response status line
        Debug.Print("HTTP/" + response.ProtocolVersion + " " +
                    response.StatusCode + " " +
                    response.StatusDescription);

        // response headers
        string[] headers = response.Headers.AllKeys;
        foreach (string name in headers)
        {
            Debug.Print(name + ": " + response.Headers[name]);
        }

        // response body
        var buffer = new byte[(int)response.ContentLength];
        Stream stream = response.GetResponseStream();
        int toRead = buffer.Length;
        while (toRead > 0)
        {
            // already read: buffer.Length - toRead
            int read = stream.Read(buffer, buffer.Length - toRead, toRead);
            toRead = toRead - read;
        }
        char[] chars = Encoding.UTF8.GetChars(buffer);
        Debug.Print(new string(chars));
    }
 string JSONResponse(HttpWebResponse webResponse)
 {
     StreamReader rdr = new StreamReader(webResponse.GetResponseStream());
     string strResponse = rdr.ReadToEnd();
     rdr.Close();
     return strResponse;
 }
Exemple #6
0
    static void write(HttpWebResponse response)
    {
        write(response.Headers);

        using (Stream data = response.GetResponseStream()) {
            using (TextReader port = new StreamReader(data)) {
                write(port);
            }
        }
    }
Exemple #7
0
        // retrieve a spot quote conversion rate from the backup data source
        private double backupRate(Currency fromCurrency, Currency toCurrency)
        {
            // compose a URL request for this specific currency as a spot request
            string          url      = backupURL + fromCurrency + toCurrency;
            HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // only if we get a successful response, retrieve and parse it
            if (response.StatusCode == HttpStatusCode.OK)
            {
                // receive the whole response into a stream of the right encoding
                Stream       receiveStream = response.GetResponseStream();
                StreamReader readStream    = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                // read the entire stream contents
                string data = readStream.ReadToEnd();

                // clean up the response and stream
                response.Close();
                readStream.Close();

                // clear the primary quotes since they do not contain the answer, and parse the lines we did receive
                dataQuotes.Clear();
                string[] lines = data.Split('\n');
                foreach (string line in lines)
                {
                    // check each line for the marker indicating the answer
                    int i1 = line.IndexOf(backupMarker);
                    if (i1 > 0)
                    {
                        // if we find that, scan until the next space
                        string s  = line.Substring(i1 + backupMarker.Length).Trim();
                        int    i2 = s.IndexOf(" ");
                        if (i2 > 0)
                        {
                            // get the data after the marker and before the space, and convert it to a double rate
                            s = s.Substring(0, i2);
                            double r       = 0;
                            bool   success = double.TryParse(s, out r);
                            if (success && (r > 0))
                            {
                                // if it's a valid positive number, return the answer
                                return(r);
                            }
                        }
                    }
                }
            }

            // if all else fails, return that we could not find the answer from the backup data source
            return(0);
        }
        //////////////////////////////////////////////////////////////////////
        /// <summary>goes to the Google auth service, and gets a new auth token</summary>
        /// <returns>the auth token, or NULL if none received</returns>
        //////////////////////////////////////////////////////////////////////
        public static string QueryClientLoginToken(GDataCredentials gc,
                                                   string serviceName,
                                                   string applicationName,
                                                   bool fUseKeepAlive,
                                                   Uri clientLoginHandler
                                                   )
        {
            Tracing.Assert(gc != null, "Do not call QueryAuthToken with no network credentials");
            if (gc == null)
            {
                throw new System.ArgumentNullException("nc", "No credentials supplied");
            }

            HttpWebRequest authRequest = WebRequest.Create(clientLoginHandler) as HttpWebRequest;

            authRequest.KeepAlive = fUseKeepAlive;

            string accountType = GoogleAuthentication.AccountType;

            if (!String.IsNullOrEmpty(gc.AccountType))
            {
                accountType += gc.AccountType;
            }
            else
            {
                accountType += GoogleAuthentication.AccountTypeDefault;
            }

            WebResponse authResponse = null;

            string authToken = null;

            try
            {
                authRequest.ContentType = HttpFormPost.Encoding;
                authRequest.Method      = HttpMethods.Post;
                ASCIIEncoding encoder = new ASCIIEncoding();

                string user = gc.Username == null ? "" : gc.Username;
                string pwd  = gc.getPassword() == null ? "" : gc.getPassword();

                // now enter the data in the stream
                string postData = GoogleAuthentication.Email + "=" + Utilities.UriEncodeUnsafe(user) + "&";
                postData += GoogleAuthentication.Password + "=" + Utilities.UriEncodeUnsafe(pwd) + "&";
                postData += GoogleAuthentication.Source + "=" + Utilities.UriEncodeUnsafe(applicationName) + "&";
                postData += GoogleAuthentication.Service + "=" + Utilities.UriEncodeUnsafe(serviceName) + "&";
                if (gc.CaptchaAnswer != null)
                {
                    postData += GoogleAuthentication.CaptchaAnswer + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaAnswer) + "&";
                }
                if (gc.CaptchaToken != null)
                {
                    postData += GoogleAuthentication.CaptchaToken + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaToken) + "&";
                }
                postData += accountType;

                byte[] encodedData = encoder.GetBytes(postData);
                authRequest.ContentLength = encodedData.Length;

                Stream requestStream = authRequest.GetRequestStream();
                requestStream.Write(encodedData, 0, encodedData.Length);
                requestStream.Close();
                authResponse = authRequest.GetResponse();
            }
            catch (WebException e)
            {
                Tracing.TraceMsg("QueryAuthtoken failed " + e.Status + " " + e.Message);
                throw;
            }
            HttpWebResponse response = authResponse as HttpWebResponse;

            if (response != null)
            {
                // check the content type, it must be text
                if (!response.ContentType.StartsWith(HttpFormPost.ReturnContentType))
                {
                    throw new GDataRequestException("Execution of authentication request returned unexpected content type: " + response.ContentType, response);
                }
                TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream());
                authToken = Utilities.FindToken(tokens, GoogleAuthentication.AuthToken);

                if (authToken == null)
                {
                    throw Utilities.getAuthException(tokens, response);
                }
                // failsafe. if getAuthException did not catch an error...
                int code = (int)response.StatusCode;
                if (code != 200)
                {
                    throw new GDataRequestException("Execution of authentication request returned unexpected result: " + code, response);
                }
            }
            Tracing.Assert(authToken != null, "did not find an auth token in QueryAuthToken");
            if (authResponse != null)
            {
                authResponse.Close();
            }

            return(authToken);
        }
Exemple #9
0
        /// <summary>
        /// This feature allows you to make collections using a Token code that was previously created by our system,
        /// and which was used to store your customers’ credit cards data safely.
        /// </summary>
        /// <param name="isTest"></param>
        /// <param name="pCommand"></param>
        /// <param name="pLanguage"></param>
        /// <param name="pCreditCardTokenId"></param>
        /// <param name="pTX_VALUE"></param>
        /// <param name="pBuyer"></param>
        /// <param name="pOrderShippingAddress"></param>
        /// <param name="pPayer"></param>
        /// <param name="pExtraParameters"></param>
        /// <param name="pPaymentCountry"></param>
        /// <param name="pPaymentMethod"></param>
        /// <param name="pType"></param>
        /// <param name="pUserAgent"></param>
        /// <param name="pDescription"></param>
        /// <param name="pNotifyUrl"></param>
        /// <param name="pReferenceCode"></param>
        /// <param name="pCookie"></param>
        /// <param name="pDeviceSessionId"></param>
        /// <param name="pIpAddress"></param>
        /// <returns></returns>
        public static async Task <RootPayUIndividualPaymentWithTokenResponse> IndividualPaymentWithToken(bool isTest, string pCommand, string pLanguage,
                                                                                                         string pCreditCardTokenId, Request_TXVALUE pTX_VALUE, bool calculateTaxes,
                                                                                                         Request_IndividualPaymentWithToken_Buyer pBuyer, Address pOrderShippingAddress,
                                                                                                         Request_IndividualPaymentWithToken_Payer pPayer, Request_ExtraParameters pExtraParameters, string pPaymentCountry,
                                                                                                         string pPaymentMethod, string pType, string pUserAgent, string pDescription, string pNotifyUrl, string pReferenceCode,
                                                                                                         string pCookie, string pDeviceSessionId, string pIpAddress)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestMerchantId = ConfigurationManager.AppSettings["PAYU_API_MERCHANTID"];

                int productionOrTestAccountId = int.Parse(ConfigurationManager.AppSettings["PAYU_API_ACCOUNTID"]);

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionPaymentsConnectionUrl;

                var url = productionOrTestUrl;
                if (url != null)
                {
                    string source = productionOrTestApiKey + "~" + productionOrTestMerchantId + "~" + pReferenceCode + "~" +
                                    pTX_VALUE.value + "~" + pTX_VALUE.currency;
                    MD5    md5Hash    = MD5.Create();
                    string pSignature = CryptoHelper.GetMd5Hash(md5Hash, source);

                    var jsonObject = new RootPayUIndividualPaymentWithTokenRequest()
                    {
                        command  = pCommand,
                        language = pLanguage,
                        merchant = new Merchant()
                        {
                            apiKey   = productionOrTestApiKey,
                            apiLogin = productionOrTestApiLogIn
                        },
                        transaction = new Request_IndividualPaymentWithToken_Transaction()
                        {
                            cookie            = pCookie,
                            creditCardTokenId = pCreditCardTokenId,
                            deviceSessionId   = pDeviceSessionId,
                            userAgent         = pUserAgent,
                            ipAddress         = pIpAddress,
                            paymentCountry    = pPaymentCountry,
                            paymentMethod     = pPaymentMethod,
                            type  = pType,
                            payer = pPayer,
                            order = new Request_IndividualPaymentWithToken_Order()
                            {
                                accountId        = productionOrTestAccountId,
                                buyer            = pBuyer,
                                description      = pDescription,
                                language         = pLanguage,
                                notifyUrl        = pNotifyUrl,
                                referenceCode    = pReferenceCode,
                                shippingAddress  = pOrderShippingAddress,
                                additionalValues = calculateTaxes ? new Request_AdditionalValues()
                                {
                                    TX_VALUE = pTX_VALUE,
                                    TX_TAX   = new Request_TXTAX()
                                    {
                                        currency = pTX_VALUE.currency,
                                        value    = Tax_BaseReturnHelper.CalculateTaxValue(pTX_VALUE.value)
                                    },
                                    TX_TAX_RETURN_BASE = new Request_TXTAXRETURNBASE()
                                    {
                                        currency = pTX_VALUE.currency,
                                        value    = Tax_BaseReturnHelper.CalculateBaseReturnValue(pTX_VALUE.value)
                                    }
                                } : new Request_AdditionalValues()
                                {
                                    TX_VALUE = pTX_VALUE,
                                    TX_TAX   = new Request_TXTAX()
                                    {
                                        currency = pTX_VALUE.currency,
                                        value    = 0.0m
                                    },
                                    TX_TAX_RETURN_BASE = new Request_TXTAXRETURNBASE()
                                    {
                                        currency = pTX_VALUE.currency,
                                        value    = 0.0m
                                    }
                                },
                                signature = pSignature
                            },
                            extraParameters = pExtraParameters
                        },
                        test = isTest
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);


                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayUGeneralApi(url, requestJson, HttpMethod.POST);

                    if (resp == null)
                    {
                        return(null);
                    }

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();

                            var des = JsonConvert.DeserializeObject <RootPayUIndividualPaymentWithTokenResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return(des);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch
            {
                throw;
            }
            return(null);
        }
Exemple #10
0
        /// <summary>
        /// http的post请求
        /// </summary>
        /// <param name="sUrl">请求的地址</param>
        /// <param name="json">请求的参数</param>
        /// <param name="sHead">请求头</param>
        /// <param name="postType">请求类型,0:application/x-www-form-urlencoded,1:application/json,2:text/xml</param>
        public static string RawPost(string sUrl, string sBody, Dictionary <string, string> sHead = null, int?postType = 0, int iTimeoutSeconds = 30)
        {
            string sResult                    = string.Empty;
            string sError                     = string.Empty;
            string sResponseStatusCode        = string.Empty;
            string sResponseStatusDescription = string.Empty;

            HttpWebResponse oHttpWebResponse = null;
            HttpWebRequest  oHttpWebRequest  = null;
            Stream          oStream          = null;
            StreamReader    oStreamReader    = null;

            byte[] bytes = Encoding.UTF8.GetBytes(sBody);


            try
            {
                oHttpWebRequest           = (HttpWebRequest)WebRequest.Create(sUrl);
                oHttpWebRequest.KeepAlive = false;
                oHttpWebRequest.Method    = "POST";
                switch (postType)
                {
                case 0:
                    oHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    break;

                case 1:
                    oHttpWebRequest.ContentType = "application/json";
                    break;

                case 2:
                    oHttpWebRequest.ContentType = "text/xml";
                    break;

                default:
                    oHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    break;
                }

                oHttpWebRequest.ContentLength = bytes.Length;

                //添加请求头
                if (sHead != null && sHead.Count > 0)
                {
                    foreach (var item in sHead)
                    {
                        oHttpWebRequest.Headers.Add(item.Key, item.Value);
                    }
                }

                oHttpWebRequest.Timeout = 1000 * iTimeoutSeconds;

                oStream = oHttpWebRequest.GetRequestStream();
                oStream.Write(bytes, 0, bytes.Length);
                oStream.Close();

                oHttpWebResponse = (HttpWebResponse)oHttpWebRequest.GetResponse();

                oStreamReader              = new StreamReader(oHttpWebResponse.GetResponseStream());
                sResponseStatusCode        = oHttpWebResponse.StatusCode.ToString();
                sResponseStatusDescription = oHttpWebResponse.StatusDescription;


                sResult = oStreamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                sError += "!!Error: " + ex.Message + "\r\n";
                sError += "    Message: " + ex.Message + "\r\n";
                sError += "    InnerException: " + ex.InnerException + "\r\n";
                sError += "\r\n";
                sError += "    StackTrace: " + ex.StackTrace + "\r\n";

                Console.WriteLine(sError);
            }
            finally
            {
                oStream = null;
                if (oStream != null)
                {
                    oStream.Close();
                }
                if (oHttpWebRequest != null)
                {
                    oHttpWebRequest.Abort();
                }
                if (oHttpWebResponse != null)
                {
                    oHttpWebResponse.Close();
                }
                if (oStreamReader != null)
                {
                    oStreamReader.Close();
                }
            }
            StringBuilder strLog = new StringBuilder();

            strLog.AppendLine("************************日志 begin*************************");
            strLog.AppendLine("sUrl:" + sUrl);
            strLog.AppendLine("sBody:" + sBody);
            strLog.AppendLine("sResult:" + sResult);
            strLog.AppendLine("sError:" + sError);
            strLog.AppendLine("************************日志 end**************************");



            Console.WriteLine(sError);
            return(sResult);
        }
Exemple #11
0
    /// <summary>
    ///Gets the result of the HTTP Request. 
    /// </summary>
    /// <param name="response">
    /// A <see cref="HttpWebResponse"/>
    /// </param>
    /// <returns>
    /// A <see cref="String"/>
    /// </returns>
    private String HTTPResponseToString(HttpWebResponse response)
    {
        // used to build entire input
        StringBuilder sb = new StringBuilder ();

        // used on each read operation
        byte[] buf = new byte[8192];

        // we will read data via the response stream
        Stream resStream = response.GetResponseStream ();

        string tempString = null;
        int count = 0;

        do {
            // fill the buffer with data
            count = resStream.Read (buf, 0, buf.Length);

            // make sure we read some data
            if (count != 0) {
                // translate from bytes to ASCII text
                tempString = Encoding.ASCII.GetString (buf, 0, count);

                // continue building the string
                sb.Append (tempString);
            }
        } while (count > 0);
        // any more data to read?
        return sb.ToString ();
    }
Exemple #12
0
        public static T RequestServer <T>(ApiOption apiOption, Dictionary <string, object> paras, RequestType requestType = RequestType.Post)
        {
            string urlPath = GetEnumDesc <ApiOption>(apiOption);
            string url     = AppConfig.ApiUrl + urlPath;
            string paraStr = string.Empty;
            string userID  = string.Empty;

            if (paras.ContainsKey("userID"))
            {
                userID = paras["userID"].ToString();
            }
            else
            {
                userID = "BC6802E9-285C-471C-8172-3867C87803E2";
                paras.Add("userID", userID);
            }

            if (paras != null && paras.Count > 0)
            {
                paraStr += CreateParameterStr(paras);
            }
            //签名认证
            string signature = Signature.GetSignature(AppConfig.AppKey, AppConfig.AppSecret, userID);

            paraStr += "signature=" + signature;

            string strResult = string.Empty;

            try
            {
                if (requestType == RequestType.Get)
                {
                    url += "?" + paraStr;
                    Uri            uri            = new Uri(url);
                    HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;

                    httpWebRequest.Method            = "GET";
                    httpWebRequest.KeepAlive         = false;
                    httpWebRequest.AllowAutoRedirect = true;
                    httpWebRequest.ContentType       = "application/x-www-form-urlencoded";
                    httpWebRequest.UserAgent         = "Ocean/NET-SDKClient";

                    HttpWebResponse response       = httpWebRequest.GetResponse() as HttpWebResponse;
                    Stream          responseStream = response.GetResponseStream();

                    System.Text.Encoding encode = Encoding.UTF8;
                    StreamReader         reader = new StreamReader(response.GetResponseStream(), encode);
                    strResult = reader.ReadToEnd();

                    reader.Close();
                    response.Close();
                }
                else
                {
                    byte[]         postData       = Encoding.UTF8.GetBytes(paraStr);
                    Uri            uri            = new Uri(url);
                    HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;

                    httpWebRequest.Method            = "POST";
                    httpWebRequest.KeepAlive         = false;
                    httpWebRequest.AllowAutoRedirect = true;
                    httpWebRequest.ContentType       = "application/x-www-form-urlencoded";
                    httpWebRequest.UserAgent         = "Ocean/NET-SDKClient";
                    httpWebRequest.ContentLength     = postData.Length;

                    System.IO.Stream outputStream = httpWebRequest.GetRequestStream();
                    outputStream.Write(postData, 0, postData.Length);
                    outputStream.Close();
                    HttpWebResponse response       = httpWebRequest.GetResponse() as HttpWebResponse;
                    Stream          responseStream = response.GetResponseStream();

                    System.Text.Encoding encode = Encoding.UTF8;
                    StreamReader         reader = new StreamReader(response.GetResponseStream(), encode);
                    strResult = reader.ReadToEnd();

                    reader.Close();
                    response.Close();
                }
            }
            catch (System.Net.WebException webException)
            {
                HttpWebResponse response       = webException.Response as HttpWebResponse;
                Stream          responseStream = response.GetResponseStream();
                StreamReader    reader         = new StreamReader(responseStream, Encoding.UTF8);
                strResult = reader.ReadToEnd();

                reader.Close();
                response.Close();
            }



            return(JsonConvert.DeserializeObject <T>(strResult));
        }
Exemple #13
0
        private HttpResponseMessage CreateResponseMessage(HttpWebResponse webResponse, HttpRequestMessage request)
        {
            HttpResponseMessage response = new HttpResponseMessage(webResponse.StatusCode,
                webResponse.StatusDescription);
            response.Version = webResponse.ProtocolVersion;
            response.RequestMessage = request;
            response.Content = new StreamContent(webResponse.GetResponseStream());

            // Update Request-URI to reflect the URI actually leading to the response message.
            request.RequestUri = webResponse.ResponseUri;

            WebHeaderCollection webResponseHeaders = webResponse.Headers;
            HttpContentHeaders contentHeaders = response.Content.Headers;
            HttpResponseHeaders responseHeaders = response.Headers;

            // HttpWebResponse.ContentLength is set to -1 if no Content-Length header is provided.
            if (webResponse.ContentLength >= 0)
            {
                contentHeaders.ContentLength = webResponse.ContentLength;
            }

            for (int i = 0; i < webResponseHeaders.Count; i++)
            {
                string currentHeader = webResponseHeaders.GetKey(i);

                if (knownContentHeaders.Contains(currentHeader))
                {
                    // We already set Content-Length
                    if (string.Compare(currentHeader, HttpKnownHeaderNames.ContentLength,
                        StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        continue;
                    }

                    AddHeaderValues(webResponseHeaders, i, currentHeader, contentHeaders);
                }
                else
                {
                    AddHeaderValues(webResponseHeaders, i, currentHeader, responseHeaders);
                }
            }

            return response;
        }
    private static Boolean getResponse(HttpWebRequest request)
    {
        try
        {
            response = request.GetResponse() as HttpWebResponse;
            return true;
        }
        catch (WebException e)
        {
            Console.WriteLine("Exception Message :" + e.Message);
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                var response = ((HttpWebResponse)e.Response);
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                var text = reader.ReadToEnd();
                int stPos = text.LastIndexOf(":");
                int endPos = text.LastIndexOf("}");
                WPHelper.permissionErrorMsg = text.Substring(stPos + 1, endPos - stPos) == null ? text : text.Substring(stPos + 1, (endPos - stPos-1));
                Console.WriteLine("Response Description : {0}", text);
            }
            return false;
        }
    }
Exemple #15
0
    /// <summary>
    /// 根据相传入的数据,得到相应页面数据
    /// </summary>
    /// <param name="strPostdata">传入的数据Post方式,get方式传NUll或者空字符串都可以</param>
    /// <returns>string类型的响应数据</returns>
    private string GetHttpRequestData(string strPostdata)
    {
        try
        {
            //支持跳转页面,查询结果将是跳转后的页面
            request.AllowAutoRedirect = true;

            //验证在得到结果时是否有传入数据
            if (!string.IsNullOrEmpty(strPostdata) && request.Method.Trim().ToLower().Contains("post"))
            {
                byte[] buffer = encoding.GetBytes(strPostdata);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }

            ////最大连接数
            //request.ServicePoint.ConnectionLimit = 1024;

            #region 得到请求的response

            using (response = (HttpWebResponse)request.GetResponse())
            {
                //从这里开始我们要无视编码了
                if (encoding == null)
                {
                    MemoryStream _stream = new MemoryStream();
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(response.GetResponseStream());
                    }
                    else
                    {
                        //response.GetResponseStream().CopyTo(_stream, 10240);
                        // .net4.0以下写法
                        _stream = GetMemoryStream(response.GetResponseStream());
                    }
                    byte[] RawResponse = _stream.ToArray();
                    string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
                    //<meta(.*?)charset([\s]?)=[^>](.*?)>
                    Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
                    charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty);
                    if (charter.Length > 0)
                    {
                        charter = charter.ToLower().Replace("iso-8859-1", "gbk");
                        encoding = Encoding.GetEncoding(charter);
                    }
                    else
                    {
                        if (response.CharacterSet.ToLower().Trim() == "iso-8859-1")
                        {
                            encoding = Encoding.GetEncoding("gbk");
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(response.CharacterSet.Trim()))
                            {
                                encoding = Encoding.UTF8;
                            }
                            else
                            {
                                encoding = Encoding.GetEncoding(response.CharacterSet);
                            }
                        }
                    }
                    returnData = encoding.GetString(RawResponse);
                }
                else
                {
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
                        {
                            returnData = reader.ReadToEnd();
                        }
                    }
                    else
                    {
                        //开始读取流并设置编码方式
                        using (reader = new StreamReader(response.GetResponseStream(), encoding))
                        {
                            returnData = reader.ReadToEnd();
                        }
                    }
                }
            }

            #endregion
        }
        catch (WebException ex)
        {
            //这里是在发生异常时返回的错误信息
            returnData = "String Error";
            response = (HttpWebResponse)ex.Response;
        }
        if (isToLower)
        {
            returnData = returnData.ToLower();
        }
        return returnData;
    }
            protected ResponseRecord populateResponseRecord(HttpWebResponse response)
            {
                Stream responseStream = response.GetResponseStream();

                ResponseRecord responseRecord = new ResponseRecord();
                responseRecord.ResponseHeaders = response.Headers;
                responseRecord.ResponseStream = responseStream;

                return responseRecord;
            }
Exemple #17
0
        /// <summary>
        /// 使用Post方法获取字符串结果
        /// 主要用于文件上传(可携带表单数据)
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="formItems">Post表单文件、内容数据</param>
        /// <returns></returns>
        public static string PostForm(string url, List <FormItemModel> formItems)
        {
            string          result   = "";
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;
            Stream          stream   = null;
            StreamReader    reader   = null;

            try
            {
                GC.Collect();    // 请求之前 做一次垃圾回收
                ServicePointManager.DefaultConnectionLimit = 20;
                // 打印 请求地址及参数
                LogHelper.Info("请求数据:" + url);
                request = WebRequest.Create(url) as HttpWebRequest;
                #region 初始化请求对象
                request.Accept          = "*/*";
                request.Method          = "POST";
                request.UserAgent       = "Mozilla/5.0";
                request.CookieContainer = CookieEntity.cookie;
                request.KeepAlive       = false;         // 保持短链接
                request.Timeout         = 2 * 60 * 1000; // 2分钟,以防网络超时 或 文件过大

                #endregion
                string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                //请求流
                var postStream = new MemoryStream();
                #region 处理Form表单请求内容
                //是否用Form上传文件
                var formUploadFile = formItems != null && formItems.Count > 0;
                if (formUploadFile)
                {
                    //文件数据模板
                    string fileFormdataTemplate =
                        "\r\n--" + boundary +
                        "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
                        "\r\nContent-Type: multipart/form-data" +
                        "\r\n\r\n";
                    //文本数据模板
                    string dataFormdataTemplate =
                        "\r\n--" + boundary +
                        "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                        "\r\n\r\n{1}";
                    foreach (var item in formItems)
                    {
                        string formdata = null;
                        if (item.IsFile)
                        {
                            //上传文件
                            formdata = string.Format(
                                fileFormdataTemplate,
                                item.Key, //表单键
                                item.FileName);
                        }
                        else
                        {
                            //上传文本
                            formdata = string.Format(
                                dataFormdataTemplate,
                                item.Key,
                                item.Value);
                        }

                        //统一处理
                        byte[] formdataBytes = null;
                        //第一行不需要换行
                        if (postStream.Length == 0)
                        {
                            formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
                        }
                        else
                        {
                            formdataBytes = Encoding.UTF8.GetBytes(formdata);
                        }
                        postStream.Write(formdataBytes, 0, formdataBytes.Length);

                        //写入文件内容
                        if (item.FileContent != null && item.FileContent.Length > 0)
                        {
                            using (var streams = item.FileContent)
                            {
                                byte[] buffer    = new byte[1024];
                                int    bytesRead = 0;
                                while ((bytesRead = streams.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    postStream.Write(buffer, 0, bytesRead);
                                }
                            }
                        }
                    }
                    //结尾
                    var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                    postStream.Write(footer, 0, footer.Length);
                }
                else
                {
                    request.ContentType = "application/json;charset=UTF-8";
                }
                #endregion
                request.ContentLength = postStream.Length;
                #region 输入二进制流
                if (postStream != null)
                {
                    postStream.Position = 0;
                    //直接写入流
                    Stream requestStream = request.GetRequestStream();

                    byte[] buffer    = new byte[1024];
                    int    bytesRead = 0;
                    while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                    postStream.Close();//关闭文件访问
                }
                #endregion
                response            = (HttpWebResponse)request.GetResponse();
                CookieEntity.cookie = request.CookieContainer;
                stream = response.GetResponseStream();
                reader = new StreamReader(stream, Encoding.UTF8);
                result = reader.ReadToEnd().Trim();
                // 打印响应结果
                LogHelper.Info("响应结果:" + result);
            }
            catch (Exception e)
            {
                result = e.Message;
                LogHelper.Error(e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return(result);;
        }
Exemple #18
0
        public void ReadBegin(object aResult)
        {
            HttpWebRequest request = aResult as HttpWebRequest;

            HttpWebResponse response  = null;
            Stream          resStream = null;

            try
            {
                response  = request.GetResponse() as HttpWebResponse;
                resStream = response.GetResponseStream();

                iReadDocument = new XmlDocument();
                iReadDocument.Load(resStream);

                XmlNamespaceManager xmlNsMan = new XmlNamespaceManager(iReadDocument.NameTable);
                xmlNsMan.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    xmlNsMan.AddNamespace("u", Upnp.ServiceTypeToString(iService.Type));
                    XmlNodeList nodeList = iReadDocument.SelectNodes(string.Format("/s:Envelope/s:Body/u:{0}Response", iAction.Name), xmlNsMan);
                    if (nodeList.Count == 1)
                    {
                        iResponse = nodeList[0].ChildNodes;
                        iIndex    = 0;
                    }
                    else
                    {
                        throw new ServiceException(600, "Invalid response: " + iReadDocument.OuterXml);
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    response  = e.Response as HttpWebResponse;
                    resStream = response.GetResponseStream();

                    if (response.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        XmlDocument document = new XmlDocument();
                        document.Load(resStream);

                        XmlNamespaceManager xmlNsMan = new XmlNamespaceManager(document.NameTable);
                        xmlNsMan.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
                        xmlNsMan.AddNamespace("c", "urn:schemas-upnp-org:control-1-0");

                        string  faultCode     = string.Empty;
                        XmlNode faultCodeNode = document.SelectSingleNode("/s:Envelope/s:Body/s:Fault/faultcode", xmlNsMan);
                        if (faultCodeNode != null)
                        {
                            faultCode = faultCodeNode.InnerText;
                        }
                        string  faultString     = string.Empty;
                        XmlNode faultStringNode = document.SelectSingleNode("/s:Envelope/s:Body/s:Fault/faultstring", xmlNsMan);
                        if (faultStringNode != null)
                        {
                            faultString = faultStringNode.InnerText;
                        }
                        XmlNode detail = document.SelectSingleNode("/s:Envelope/s:Body/s:Fault/detail", xmlNsMan);
                        throw new SoapException(faultString, new XmlQualifiedName(faultCode), string.Empty, detail);
                    }

                    throw new ServiceException(600, "Invalid response: " + response.StatusDescription);
                }

                throw new Exception(e.Status.ToString());
            }
            finally
            {
                if (resStream != null)
                {
                    resStream.Close();
                    resStream.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
        public HTTPPost(Uri Url, Dictionary<string, string> Parameters)
        {
            StringBuilder respBody = new StringBuilder();

            request = (HttpWebRequest)HttpWebRequest.Create(Url);
            request.UserAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C10 Safari/419.3";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string content = "?";
            foreach (string k in Parameters.Keys)
            {
                content += k + "=" + Parameters[k] + "&";
            }
            content = content.TrimEnd(new char[] { '&' });
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(content);
            request.ContentLength = byte1.Length;
            byte[] buf = new byte[8192];
            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(byte1, 0, byte1.Length);
                rs.Close();

                response = (HttpWebResponse)request.GetResponse();
                Stream respStream = response.GetResponseStream();

                int count = 0;
                do
                {
                    count = respStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                        respBody.Append(Encoding.ASCII.GetString(buf, 0, count));
                }
                while (count > 0);

                respStream.Close();
                ResponseBody = respBody.ToString();
                EscapedBody = GetEscapedBody();
                StatusCode = GetStatusLine();
                Headers = GetHeaders();

                response.Close();
            }
        }
Exemple #20
0
        private void LoadConnection(object sender, DoWorkEventArgs e)
        {
            if (_clientChangelogDownloader.IsBusy)
            {
                return;
            }
            bool   blnChummerVersionGotten = true;
            string strError = LanguageManager.GetString("String_Error", GlobalOptions.Language).Trim();

            _strExceptionString = string.Empty;
            LatestVersion       = strError;
            string strUpdateLocation = _blnPreferNightly
                ? "https://api.github.com/repos/chummer5a/chummer5a/releases"
                : "https://api.github.com/repos/chummer5a/chummer5a/releases/latest";

            HttpWebRequest request = null;

            try
            {
                WebRequest objTemp = WebRequest.Create(strUpdateLocation);
                request = objTemp as HttpWebRequest;
            }
            catch (System.Security.SecurityException)
            {
                blnChummerVersionGotten = false;
            }
            if (request == null)
            {
                blnChummerVersionGotten = false;
            }
            if (blnChummerVersionGotten)
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.Accept    = "application/json";
                request.Timeout   = 5000;

                // Get the response.
                HttpWebResponse response = null;
                try
                {
                    response = request.GetResponse() as HttpWebResponse;
                }
                catch (WebException ex)
                {
                    blnChummerVersionGotten = false;
                    string strException       = ex.ToString();
                    int    intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (intNewLineLocation == -1)
                    {
                        intNewLineLocation = strException.IndexOf('\n');
                    }
                    if (intNewLineLocation != -1)
                    {
                        strException = strException.Substring(0, intNewLineLocation);
                    }
                    _strExceptionString = strException;
                }

                if (_workerConnectionLoader.CancellationPending)
                {
                    e.Cancel = true;
                    response?.Close();
                    return;
                }

                // Get the stream containing content returned by the server.
                Stream dataStream = response?.GetResponseStream();
                if (dataStream == null)
                {
                    blnChummerVersionGotten = false;
                }
                if (blnChummerVersionGotten)
                {
                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        dataStream.Close();
                        response.Close();
                        return;
                    }
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream, Encoding.UTF8, true);
                    // Read the content.

                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        reader.Close();
                        response.Close();
                        return;
                    }

                    string responseFromServer = reader.ReadToEnd();

                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        reader.Close();
                        response.Close();
                        return;
                    }

                    string[] stringSeparators = { "," };

                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        reader.Close();
                        response.Close();
                        return;
                    }

                    string[] result = responseFromServer.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                    bool blnFoundTag     = false;
                    bool blnFoundArchive = false;
                    foreach (string line in result)
                    {
                        if (_workerConnectionLoader.CancellationPending)
                        {
                            e.Cancel = true;
                            reader.Close();
                            response.Close();
                            return;
                        }
                        if (!blnFoundTag && line.Contains("tag_name"))
                        {
                            _strLatestVersion = line.Split(':')[1];
                            LatestVersion     = _strLatestVersion.Split('}')[0].FastEscape('\"').Trim();
                            blnFoundTag       = true;
                            if (blnFoundArchive)
                            {
                                break;
                            }
                        }
                        if (!blnFoundArchive && line.Contains("browser_download_url"))
                        {
                            _strDownloadFile = line.Split(':')[2];
                            _strDownloadFile = _strDownloadFile.Substring(2);
                            _strDownloadFile = _strDownloadFile.Split('}')[0].FastEscape('\"');
                            _strDownloadFile = "https://" + _strDownloadFile;
                            blnFoundArchive  = true;
                            if (blnFoundTag)
                            {
                                break;
                            }
                        }
                    }
                    if (!blnFoundArchive || !blnFoundTag)
                    {
                        blnChummerVersionGotten = false;
                    }
                    // Cleanup the streams and the response.
                    reader.Close();
                }
                dataStream?.Close();
                response?.Close();
            }
            if (!blnChummerVersionGotten || LatestVersion == strError)
            {
                MessageBox.Show(
                    string.IsNullOrEmpty(_strExceptionString)
                        ? LanguageManager.GetString("Warning_Update_CouldNotConnect", GlobalOptions.Language)
                        : string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), _strExceptionString), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                _blnIsConnected = false;
                e.Cancel        = true;
            }
            else
            {
                if (File.Exists(_strTempUpdatePath))
                {
                    if (File.Exists(_strTempUpdatePath + ".old"))
                    {
                        File.Delete(_strTempUpdatePath + ".old");
                    }
                    File.Move(_strTempUpdatePath, _strTempUpdatePath + ".old");
                }
                string strURL = "https://raw.githubusercontent.com/chummer5a/chummer5a/" + LatestVersion + "/Chummer/changelog.txt";
                try
                {
                    Uri uriConnectionAddress = new Uri(strURL);
                    if (File.Exists(_strTempUpdatePath + ".tmp"))
                    {
                        File.Delete(_strTempUpdatePath + ".tmp");
                    }
                    _clientChangelogDownloader.DownloadFileAsync(uriConnectionAddress, _strTempUpdatePath + ".tmp");
                    while (_clientChangelogDownloader.IsBusy)
                    {
                        if (_workerConnectionLoader.CancellationPending)
                        {
                            _clientChangelogDownloader.CancelAsync();
                            e.Cancel = true;
                            return;
                        }
                    }
                    File.Move(_strTempUpdatePath + ".tmp", _strTempUpdatePath);
                }
                catch (WebException ex)
                {
                    string strException       = ex.ToString();
                    int    intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (intNewLineLocation == -1)
                    {
                        intNewLineLocation = strException.IndexOf('\n');
                    }
                    if (intNewLineLocation != -1)
                    {
                        strException = strException.Substring(0, intNewLineLocation);
                    }
                    _strExceptionString = strException;
                    MessageBox.Show(string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), strException), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _blnIsConnected = false;
                    e.Cancel        = true;
                }
                catch (UriFormatException ex)
                {
                    string strException       = ex.ToString();
                    int    intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (intNewLineLocation == -1)
                    {
                        intNewLineLocation = strException.IndexOf('\n');
                    }
                    if (intNewLineLocation != -1)
                    {
                        strException = strException.Substring(0, intNewLineLocation);
                    }
                    _strExceptionString = strException;
                    MessageBox.Show(string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), strException), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _blnIsConnected = false;
                    e.Cancel        = true;
                }
            }
        }
Exemple #21
0
		HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage)
		{
			var response = new HttpResponseMessage (wr.StatusCode);
			response.RequestMessage = requestMessage;
			response.ReasonPhrase = wr.StatusDescription;
			response.Content = new StreamContent (wr.GetResponseStream ());

			var headers = wr.Headers;
			for (int i = 0; i < headers.Count; ++i) {
				var key = headers.GetKey(i);
				var value = headers.GetValues (i);

				if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content)
					response.Content.Headers.AddWithoutValidation (key, value);
				else
					response.Headers.AddWithoutValidation (key, value);
			}

			return response;
		}
 private static void CopyResponseStream(HttpContext context, HttpWebResponse res)
 {
     //Copy response data or redirect
     context.Response.StatusCode = (int)res.StatusCode;
     using (var resStream = res.GetResponseStream())
     {
         if (string.IsNullOrEmpty(res.CharacterSet)) // Binary response (image)
         {
             var resBytes = new byte[res.ContentLength];
             resStream.Read(resBytes, 0, resBytes.Length);
             context.Response.OutputStream.Write(resBytes, 0, resBytes.Length);
         }
         else
         {
             var enc = Encoding.GetEncoding(res.CharacterSet); // text response
             using (var rd = new System.IO.StreamReader(resStream))
             {
                 var resString = rd.ReadToEnd();
                 context.Response.Output.Write(resString);
             }
         }
     }
 }
Exemple #23
0
        public static string GetBody(HttpWebResponse response)
        {
            try {
                Stream dataStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(dataStream);

                string body = reader.ReadToEnd();

                dataStream.Close();
                reader.Close();

                return body;
            }
            catch(Exception)
            {
                return null;
            }
        }
		public static ICrossDomainPolicy BuildSilverlightPolicy (HttpWebResponse response)
		{
			// return null if no Silverlight policy was found, since we offer a second chance with a flash policy
			if ((response.StatusCode != HttpStatusCode.OK) || !CheckContentType (response.ContentType))
				return null;

			ICrossDomainPolicy policy = null;
			try {
				policy = ClientAccessPolicy.FromStream (response.GetResponseStream ());
				if (policy != null)
					AddPolicy (response.ResponseUri, policy);
			} catch (Exception ex) {
				Console.WriteLine (String.Format ("CrossDomainAccessManager caught an exception while reading {0}: {1}", 
					response.ResponseUri, ex));
				// and ignore.
			}
			return policy;
		}
Exemple #25
0
 /// <summary>
 /// 根据相传入的数据,得到相应页面数据
 /// </summary>
 /// <param name="item">参数类对象</param>
 /// <returns>返回HttpResult类型</returns>
 public HttpResult GetHtml(HttpItem item)
 {
     //返回参数
     HttpResult result = new HttpResult();
     try
     {
         //准备参数
         SetRequest(item);
     }
     catch (Exception ex)
     {
         return new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错:" + ex.Message };
     }
     try
     {
         #region 得到请求的response
         using (response = (HttpWebResponse)request.GetResponse())
         {
             result.StatusCode = response.StatusCode;
             result.StatusDescription = response.StatusDescription;
             result.Header = response.Headers;
             if (response.Cookies != null) result.CookieCollection = response.Cookies;
             if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
             byte[] ResponseByte = null;
             using (MemoryStream _stream = new MemoryStream())
             {
                 //GZIIP处理
                 if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                 {
                     //开始读取流并设置编码方式
                     new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                 }
                 else
                 {
                     //开始读取流并设置编码方式
                     response.GetResponseStream().CopyTo(_stream, 10240);
                 }
                 //获取Byte
                 ResponseByte = _stream.ToArray();
             }
             if (ResponseByte != null & ResponseByte.Length > 0)
             {
                 //是否返回Byte类型数据
                 if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
                 //从这里开始我们要无视编码了
                 if (encoding == null)
                 {
                     Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                     string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToLower().Trim() : string.Empty;
                     if (c.Length > 2)
                     {
                         try
                         {
                             if (c.IndexOf(" ") > 0) c = c.Substring(0, c.IndexOf(" "));
                             encoding = Encoding.GetEncoding(c.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
                         }
                         catch
                         {
                             if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8;
                             else encoding = Encoding.GetEncoding(response.CharacterSet);
                         }
                     }
                     else
                     {
                         if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8;
                         else encoding = Encoding.GetEncoding(response.CharacterSet);
                     }
                 }
                 //得到返回的HTML
                 result.Html = encoding.GetString(ResponseByte);
             }
             else
             {
                 //得到返回的HTML
                 result.Html = "本次请求并未返回任何数据";
             }
         }
         #endregion
     }
     catch (WebException ex)
     {
         //这里是在发生异常时返回的错误信息
         response = (HttpWebResponse)ex.Response;
         result.Html = ex.Message;
         if (response != null)
         {
             result.StatusCode = response.StatusCode;
             result.StatusDescription = response.StatusDescription;
         }
     }
     catch (Exception ex)
     {
         result.Html = ex.Message;
     }
     if (item.IsToLower) result.Html = result.Html.ToLower();
     return result;
 }
Exemple #26
0
        /// <summary>
        /// 此方法未用到
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath"></param>
        /// <param name="cc"></param>
        /// <returns></returns>
        public static string HttpPostWithCookie(string url, string filePath, CookieContainer cc)
        {
            string          html             = string.Empty;
            Stream          myResponseStream = null;
            StreamReader    sreamReader      = null;
            StreamWriter    myStreamWriter   = null;
            HttpWebResponse response         = null;

            //set file to post
            FileInfo f          = new FileInfo(filePath);
            int      fileLength = (int)f.Length;

            byte[] bufPost = new byte[fileLength];

            FileStream fStream = new FileStream(filePath, FileMode.Open);

            fStream.Read(bufPost, 0, fileLength);

            //create a http web request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //set request type
            request.Method        = "POST";
            request.ContentType   = "application/octet-stream";
            request.ContentLength = bufPost.Length;
            request.UserAgent     = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
            request.Accept        = "*/*";
            request.Referer       = "http://upload.cnblogs.com/imageuploader/upload?host=www.cnblogs.com&editor=4";
            request.KeepAlive     = true;

            //set cookie
            request.CookieContainer = cc;


            try
            {
                //get request stream
                Stream responseStream = request.GetRequestStream();
                //用StreamWriter向流request stream中写入字符,格式是UTF8
                myStreamWriter = new StreamWriter(responseStream, Encoding.UTF8);
                myStreamWriter.Write(bufPost);

                request.ServicePoint.ConnectionLimit = 50;

                try
                {
                    //get http response
                    response = request.GetResponse() as HttpWebResponse;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                //获取服务器的cookie
                //response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                //得到response stream
                myResponseStream = response.GetResponseStream();
                //用StreamReader解析response stream
                sreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                //将流转化成字符串
                html = sreamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(html);
        }
Exemple #27
0
        private object ProcessDownloadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));
                memoryStream.Flush();

                webRequest.ContentLength = memoryStream.Position;
                Stream requestStream = webRequest.GetRequestStream();
                CopyStreamContent(memoryStream, requestStream);

                requestStream.Flush();
                requestStream.Close();

                // Fire the Before request handler
                this.FirePreRequestHandler(webRequest);
            }

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSet changeSet = new ChangeSet();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                        case ReaderItemType.Entry:
                            changeSet.AddItem(this._syncReader.GetItem());
                            break;

                        case ReaderItemType.SyncBlob:
                            changeSet.ServerBlob = this._syncReader.GetServerBlob();
                            break;

                        case ReaderItemType.HasMoreChanges:
                            changeSet.IsLastBatch = !this._syncReader.GetHasMoreChangesValue();
                            break;
                        }
                    }

                    this.FirePostResponseHandler(webResponse);
                }

                webResponse.Close();

                return(changeSet);
            }
            else
            {
                throw new CacheControllerException(
                          string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                        webResponse.StatusCode,
                                        webResponse.StatusDescription));
            }
        }
Exemple #28
0
        public void Upload_Request()
        {
            Debug.Log("Upload_Request " + url);

            try
            {
                string boundary      = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endbytes      = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                //1.HttpWebRequest
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method      = "POST";
                request.KeepAlive   = true;
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Expect      = null;

                using (Stream stream = request.GetRequestStream())
                {
                    //1.1 key/value
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                    if (data != null)
                    {
                        foreach (string key in data.Keys)
                        {
                            stream.Write(boundarybytes, 0, boundarybytes.Length);
                            string formitem      = string.Format(formdataTemplate, key, data[key]);
                            byte[] formitembytes = encoding.GetBytes(formitem);
                            stream.Write(formitembytes, 0, formitembytes.Length);
                        }
                    }

                    //1.2 file
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: text/plain\r\n\r\n";
                    byte[] buffer         = new byte[4096];
                    int    bytesRead      = 0;
                    for (int i = 0; i < files.Length; i++)
                    {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string header      = string.Format(headerTemplate, "file", Path.GetFileName(files[i]));
                        byte[] headerbytes = encoding.GetBytes(header);
                        stream.Write(headerbytes, 0, headerbytes.Length);
                        using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
                        {
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                stream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }

                    //1.3 form end
                    stream.Write(endbytes, 0, endbytes.Length);
                }
                //2.WebResponse
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                {
                    string result = stream.ReadToEnd();
                    if (result == "ok")
                    {
                        Debug.Log(files[0] + " 上传完成 " + result);
                        if (callBack != null)
                        {
                            callBack(files[0] + "上传完成 " + result);
                        }
                    }
                    else
                    {
                        Debug.Log(files[0] + "上传失败 " + result);
                        if (callBack != null)
                        {
                            callBack(files[0] + "上传失败 " + result);
                        }
                    }

                    return;
                    //return stream.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Debug.Log(files[0] + "上传失败 " + e.ToString());
                if (callBack != null)
                {
                    callBack(files[0] + "上传完成 " + e.ToString());
                }
            }
        }
Exemple #29
0
        private object ProcessUploadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in request.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (TempIdToEntityMapping == null)
                        {
                            TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }
                        tempId = Guid.NewGuid().ToString();
                        TempIdToEntityMapping.Add(tempId, entity);
                    }

                    this._syncWriter.AddItem(entity, tempId);
                }

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));

                memoryStream.Flush();
                // Set the content length
                webRequest.ContentLength = memoryStream.Position;

                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    CopyStreamContent(memoryStream, requestStream);

                    // Close the request stream
                    requestStream.Flush();
                    requestStream.Close();
                }
            }

            // Fire the Before request handler
            this.FirePreRequestHandler(webRequest);

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSetResponse changeSetResponse = new ChangeSetResponse();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                        case ReaderItemType.Entry:
                            IOfflineEntity entity      = this._syncReader.GetItem();
                            IOfflineEntity ackedEntity = entity;
                            string         tempId      = null;

                            // If conflict only one temp ID should be set
                            if (this._syncReader.HasTempId() && this._syncReader.HasConflictTempId())
                            {
                                throw new CacheControllerException(string.Format("Service returned a TempId '{0}' in both live and conflicting entities.",
                                                                                 this._syncReader.GetTempId()));
                            }

                            // Validate the live temp ID if any, before adding anything to the offline context
                            if (this._syncReader.HasTempId())
                            {
                                tempId = this._syncReader.GetTempId();
                                CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, entity, tempId, changeSetResponse);
                            }

                            //  If conflict
                            if (this._syncReader.HasConflict())
                            {
                                Conflict       conflict       = this._syncReader.GetConflict();
                                IOfflineEntity conflictEntity = (conflict is SyncConflict) ?
                                                                ((SyncConflict)conflict).LosingEntity : ((SyncError)conflict).ErrorEntity;

                                // Validate conflict temp ID if any
                                if (this._syncReader.HasConflictTempId())
                                {
                                    tempId = this._syncReader.GetConflictTempId();
                                    CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, conflictEntity, tempId, changeSetResponse);
                                }

                                // Add conflict
                                changeSetResponse.AddConflict(conflict);

                                //
                                // If there is a conflict and the tempId is set in the conflict entity then the client version lost the
                                // conflict and the live entity is the server version (ServerWins)
                                //
                                if (this._syncReader.HasConflictTempId() && entity.ServiceMetadata.IsTombstone)
                                {
                                    //
                                    // This is a ServerWins conflict, or conflict error. The winning version is a tombstone without temp Id
                                    // so there is no way to map the winning entity with a temp Id. The temp Id is in the conflict so we are
                                    // using the conflict entity, which has the PK, to build a tombstone entity used to update the offline context
                                    //
                                    // In theory, we should copy the service metadata but it is the same end result as the service fills in
                                    // all the properties in the conflict entity
                                    //

                                    // Add the conflict entity
                                    conflictEntity.ServiceMetadata.IsTombstone = true;
                                    ackedEntity = conflictEntity;
                                }
                            }

                            // Add ackedEntity to storage. If ackedEntity is still equal to entity then add non-conflict entity.
                            if (!String.IsNullOrEmpty(tempId))
                            {
                                changeSetResponse.AddUpdatedItem(ackedEntity);
                            }

                            break;

                        case ReaderItemType.SyncBlob:
                            changeSetResponse.ServerBlob = this._syncReader.GetServerBlob();
                            break;
                        }
                    }
                }

                if (TempIdToEntityMapping != null && TempIdToEntityMapping.Count != 0)
                {
                    // The client sent some inserts which werent ack'd by the service. Throw.
                    StringBuilder builder = new StringBuilder("Server did not acknowledge with a permanant Id for the following tempId's: ");
                    builder.Append(string.Join(",", TempIdToEntityMapping.Keys.ToArray()));
                    throw new CacheControllerException(builder.ToString());
                }

                this.FirePostResponseHandler(webResponse);

                webResponse.Close();

                return(changeSetResponse);
            }
            else
            {
                throw new CacheControllerException(
                          string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                        webResponse.StatusCode,
                                        webResponse.StatusDescription));
            }
        }
Exemple #30
0
        /// <summary>
        /// Using this feature you can register a customer’s credit card data and get a token sequential number.
        /// </summary>
        /// <param name="pCommand"></param>
        /// <param name="pLanguage"></param>
        /// <param name="pCreditCard"></param>
        /// <returns></returns>
        public async static Task <RootPayUIndividualCreditCardRegistrationResponse> IndividualCreditCardRegistration(string pCommand, string pLanguage,
                                                                                                                     Request_IndividualCreditCardRegistration_CreditCardToken pCreditCard)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionPaymentsConnectionUrl;

                var url = productionOrTestUrl;
                if (url != null)
                {
                    var jsonObject = new RootPayUIndividualCreditCardRegistrationRequest()
                    {
                        command  = pCommand,
                        language = pLanguage,
                        merchant = new Merchant()
                        {
                            apiKey   = productionOrTestApiKey,
                            apiLogin = productionOrTestApiLogIn
                        },
                        creditCardToken = pCreditCard
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);


                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayUGeneralApi(url, requestJson, HttpMethod.POST);

                    if (resp == null)
                    {
                        return(null);
                    }

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();

                            var des = JsonConvert.DeserializeObject <RootPayUIndividualCreditCardRegistrationResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return(des);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch
            {
                throw;
            }

            return(null);
        }
Exemple #31
0
        public string GetCrimeData(double startlat, double startlong, double stoplat, double stoplong)
        {
            double       NWLong;
            double       NWLat;
            double       SELong;
            double       SELat;
            AllCrime     crimeFilter   = new AllCrime();
            List <float> filtered      = new List <float>();
            string       avoid         = "";
            string       url           = "https://data.cityofchicago.org/resource/6zsd-86xi.json";
            WebRequest   requestObject = WebRequest.Create(url);

            requestObject.Method = "GET";
            HttpWebResponse responseObject = null;

            responseObject = (HttpWebResponse)requestObject.GetResponse();

            string urlResult = null;

            using (Stream stream = responseObject.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                urlResult = sr.ReadToEnd();
                sr.Close();
            }

            crimeFilter.Property1 = JsonConvert.DeserializeObject <Class1[]>(urlResult);
            if (startlat < stoplat && startlong < stoplong)
            {
                NWLat  = stoplat;
                NWLong = startlong;
                SELat  = startlat;
                SELong = stoplong;
            }
            else if (startlat > stoplat && startlong < stoplong)
            {
                NWLat  = startlat;
                NWLong = startlong;
                SELat  = stoplat;
                SELong = stoplong;
            }
            else if (startlat > stoplat && startlong > stoplong)
            {
                NWLat  = startlat;
                NWLong = stoplong;
                SELat  = stoplat;
                SELong = startlong;
            }
            else
            {
                NWLat  = stoplat;
                NWLong = stoplong;
                SELat  = startlat;
                SELong = startlong;
            }
            for (int i = 0; i < crimeFilter.Property1.Length; i++)
            {
                try
                {
                    double longProperty = crimeFilter.Property1[i].location.coordinates[0];
                    double latProperty  = crimeFilter.Property1[i].location.coordinates[1];

                    if (longProperty >= NWLong && longProperty <= SELong)
                    {
                        if (latProperty <= NWLat && latProperty >= SELat)
                        {
                            avoid += ((latProperty + .0004) + "," + (longProperty + .0004) + ";" + (latProperty - .0004) + "," + (longProperty - .0004) + "!");
                        }
                    }
                }
                catch
                {
                }
            }
            if (avoid.Length > 0)
            {
                avoid = avoid.Remove(avoid.Length - 1);
            }


            //return avoid;
            return(avoid);
        }
Exemple #32
0
        // update the primary list of known data quotes from the primary provider
        public void updateDataQuotes()
        {
            // make a request from the primary data source URL
            HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(dataURL);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // only if we successfully received a response, receive it and process
            if (response.StatusCode == HttpStatusCode.OK)
            {
                // retrieve a stream of the response in whatever character set it is provider in
                Stream       receiveStream = response.GetResponseStream();
                StreamReader readStream    = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                // read the entire stream contents
                string data = readStream.ReadToEnd();

                // clean up the response and the stream
                response.Close();
                readStream.Close();

                // clear the list of known quotes, split the response by line feed and iterate the lines
                dataQuotes.Clear();
                string[] lines = data.Split('\n');
                foreach (string line in lines)
                {
                    // split the CSV lines into each field and break down the contents;
                    // for numeric values, attempt to parse to a valid number;
                    // for currency values, attempt to parse to a supported currency code e.g. EUR
                    string[] fields    = line.Split(',');
                    string   pair      = fields.Length >= 1 ? fields[0] : "";
                    string   timestr   = fields.Length >= 2 ? fields[1] : "";
                    string   bidbig    = fields.Length >= 3 ? fields[2] : "";
                    string   bidpts    = fields.Length >= 4 ? fields[3] : "";
                    string   askbig    = fields.Length >= 5 ? fields[4] : "";
                    string   askpts    = fields.Length >= 6 ? fields[5] : "";
                    string   bidstr    = bidbig + bidpts;
                    string   askstr    = askbig + askpts;
                    long     tsnum     = 0;
                    bool     tssuccess = long.TryParse(timestr, out tsnum);
                    if (tsnum <= 0)
                    {
                        tssuccess = false;
                    }
                    double bidnum     = 0;
                    double asknum     = 0;
                    bool   bidsuccess = double.TryParse(bidstr, out bidnum);
                    if (bidsuccess && (bidnum <= 0))
                    {
                        bidsuccess = false;
                    }
                    bool asksuccess = double.TryParse(askstr, out asknum);
                    if (asksuccess && (asknum <= 0))
                    {
                        asksuccess = false;
                    }
                    string curr1 = "";
                    string curr2 = "";
                    if (pair.Length == 7)
                    {
                        if (pair[3] == '/')
                        {
                            curr1 = pair.Substring(0, 3).ToUpper().Trim();
                            if (curr1.Length != 3)
                            {
                                curr1 = "";
                            }
                            curr2 = pair.Substring(4, 3).ToUpper().Trim();
                            if (curr2.Length != 3)
                            {
                                curr2 = "";
                            }
                        }
                    }
                    Currency[] currencies = (Currency[])Enum.GetValues(typeof(Currency)).Cast <Currency>();
                    Currency   currency1  = Currency.None;
                    Currency   currency2  = Currency.None;
                    foreach (Currency currency in currencies)
                    {
                        if (currency.ToString() == curr1)
                        {
                            currency1 = currency;
                            break;
                        }
                    }
                    foreach (Currency currency in currencies)
                    {
                        if (currency.ToString() == curr2)
                        {
                            currency2 = currency;
                            break;
                        }
                    }

                    // after parsing each field, if all are known and available, add the quote to the list of known quotes
                    if ((currency1 != Currency.None) && (currency2 != Currency.None) && bidsuccess && asksuccess && tssuccess)
                    {
                        dataQuotes.Add(new DataQuote(currency1, currency2, bidnum, asknum, tsnum));
                    }
                }

                // now that the list of known quotes has been updated, update the rate with this new information
                updateRate();
            }
        }
        private HttpStatusCode doRequest(HttpMethod httpMethod,
                                         string url,
                                         string contentType,
                                         string userName,
                                         string password,
                                         string requestPayload,
                                         out string responsePayload,
                                         bool responseStreamExpected)
        {
            HttpStatusCode statusCode = HttpStatusCode.OK;
            ASCIIEncoding  encoding   = new ASCIIEncoding();

            byte[]         buffer    = encoding.GetBytes(requestPayload);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = httpMethod.ToString();
            if (!String.IsNullOrEmpty(userName))
            {
                myRequest.Credentials = new NetworkCredential(userName, password);
            }


            if (httpMethod != HttpMethod.GET)
            {
                if (requestPayload.Length > 0)
                {
                    myRequest.ContentType   = contentType;
                    myRequest.ContentLength = buffer.Length;
                    Stream newStream = myRequest.GetRequestStream();
                    newStream.Write(buffer, 0, buffer.Length);
                    newStream.Close();
                }
            }

            HttpWebResponse myHttpWebResponse = null;

            responsePayload = "";

            try
            {
                myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();
                statusCode        = myHttpWebResponse.StatusCode;
                if (responseStreamExpected)
                {
                    Stream       streamResponse = myHttpWebResponse.GetResponseStream();
                    StreamReader streamRead     = new StreamReader(streamResponse);
                    Char[]       readBuffer     = new Char[256];
                    int          count          = streamRead.Read(readBuffer, 0, 256);
                    if (count == 0)
                    {
                        throw new Exception("Response stream is empty.");
                    }
                    while (count > 0)
                    {
                        responsePayload += new String(readBuffer, 0, count);
                        count            = streamRead.Read(readBuffer, 0, 256);
                    }
                    streamRead.Close();
                    streamResponse.Close();
                }
                myHttpWebResponse.Close();
            }
            catch (WebException webEx)
            {
                responsePayload = "";
                if (webEx.Response != null)
                {
                    Stream       streamResponse = webEx.Response.GetResponseStream();
                    StreamReader streamRead     = new StreamReader(streamResponse);
                    Char[]       readBuffer     = new Char[256];
                    int          count          = streamRead.Read(readBuffer, 0, 256);
                    while (count > 0)
                    {
                        responsePayload += new String(readBuffer, 0, count);
                        count            = streamRead.Read(readBuffer, 0, 256);
                    }
                    streamRead.Close();
                    streamResponse.Close();
                }
            }
            catch (Exception e)
            {
                statusCode      = HttpStatusCode.InternalServerError;
                responsePayload = e.Message;
            }

            return(statusCode);
        }
Exemple #34
0
        public object Invoke(
            Object clientObj,
            MethodInfo mi,
            params object[] parameters)
        {
#if (!COMPACT_FRAMEWORK)
            _responseHeaders = null;
            _responseCookies = null;
#endif
            WebRequest webReq = null;
            object     reto   = null;
            try
            {
                string useUrl = GetEffectiveUrl(clientObj);
                webReq = GetWebRequest(new Uri(useUrl));
                XmlRpcRequest req = MakeXmlRpcRequest(webReq, mi, parameters,
                                                      clientObj, _xmlRpcMethod, _id);
                SetProperties(webReq);
                SetRequestHeaders(_headers, webReq);
#if (!COMPACT_FRAMEWORK)
                SetClientCertificates(_clientCertificates, webReq);
#endif
                Stream serStream = null;
                Stream reqStream = null;
                bool   logging   = (RequestEvent != null);
                if (!logging)
                {
                    serStream = reqStream = webReq.GetRequestStream();
                }
                else
                {
                    serStream = new MemoryStream(2000);
                }
                try
                {
                    XmlRpcSerializer serializer = new XmlRpcSerializer();
                    if (_xmlEncoding != null)
                    {
                        serializer.XmlEncoding = _xmlEncoding;
                    }
                    serializer.UseIndentation    = _useIndentation;
                    serializer.Indentation       = _indentation;
                    serializer.NonStandard       = _nonStandard;
                    serializer.UseStringTag      = _useStringTag;
                    serializer.UseIntTag         = _useIntTag;
                    serializer.UseEmptyParamsTag = _useEmptyParamsTag;
                    serializer.SerializeRequest(serStream, req);
                    if (logging)
                    {
                        reqStream          = webReq.GetRequestStream();
                        serStream.Position = 0;
                        Util.CopyStream(serStream, reqStream);
                        reqStream.Flush();
                        serStream.Position = 0;
                        OnRequest(new XmlRpcRequestEventArgs(req.proxyId, req.number,
                                                             serStream));
                    }
                }
                finally
                {
                    if (reqStream != null)
                    {
                        reqStream.Close();
                    }
                }
                HttpWebResponse webResp = GetWebResponse(webReq) as HttpWebResponse;
#if (!COMPACT_FRAMEWORK)
                _responseCookies = webResp.Cookies;
                _responseHeaders = webResp.Headers;
#endif
                Stream respStm = null;
                Stream deserStream;
                logging = (ResponseEvent != null);
                try
                {
                    respStm = webResp.GetResponseStream();
                    if (!logging)
                    {
                        deserStream = respStm;
                    }
                    else
                    {
                        deserStream = new MemoryStream(2000);
                        Util.CopyStream(respStm, deserStream);
                        deserStream.Flush();
                        deserStream.Position = 0;
                    }
#if (!COMPACT_FRAMEWORK && !FX1_0)
                    deserStream = MaybeDecompressStream((HttpWebResponse)webResp,
                                                        deserStream);
#endif
                    try
                    {
                        XmlRpcResponse resp = ReadResponse(req, webResp, deserStream, null);
                        reto = resp.retVal;
                    }
                    finally
                    {
                        if (logging)
                        {
                            deserStream.Position = 0;
                            OnResponse(new XmlRpcResponseEventArgs(req.proxyId, req.number,
                                                                   deserStream));
                        }
                    }
                }
                finally
                {
                    if (respStm != null)
                    {
                        respStm.Close();
                    }
                }
            }
            finally
            {
                if (webReq != null)
                {
                    webReq = null;
                }
            }
            return(reto);
        }
Exemple #35
0
        /// <summary>
        /// Can be called syncronized to get a Http Web ResponseStream.
        /// </summary>
        /// <param name="method">The HTTP request method</param>
        /// <param name="address">Url to request</param>
        /// <param name="newAddress">out string. return a new url, if the original requested is permanent moved</param>
        /// <param name="credentials">Url credentials</param>
        /// <param name="userAgent"></param>
        /// <param name="proxy">Proxy to use</param>
        /// <param name="ifModifiedSince">Header date</param>
        /// <param name="eTag">Header tag</param>
        /// <param name="timeout">Request timeout. E.g. 60 * 1000, means one minute timeout.
        /// If zero or less than zero, the default timeout of one minute will be used</param>
        /// <param name="responseResult">out. Result of the request</param>
        /// <param name="cookie">The cookie associated with the request</param>
        /// <param name="body">The body of the HTTP request (if it is a POST)</param>
        /// <param name="additonalHeaders">These are additional headers that are being specified to the Web request</param>
        /// <returns>Stream</returns>
        public static Stream GetResponseStream(HttpMethod method, string address, out string newAddress,
                                               ICredentials credentials,
                                               string userAgent,
                                               IWebProxy proxy, ref DateTime ifModifiedSince, ref string eTag,
                                               int timeout, out RequestResult responseResult, Cookie cookie, string body,
                                               WebHeaderCollection additonalHeaders)
        {
            bool      useDefaultCred    = false;
            int       requestRetryCount = 0;
            const int MaxRetries        = 25;

            newAddress = null;

send_request:

            string requestUri = address;

            if (useDefaultCred)
            {
                credentials = CredentialCache.DefaultCredentials;
            }

            WebResponse wr =
                GetResponse(method, address, credentials, userAgent, proxy, ifModifiedSince, eTag, timeout, cookie, body,
                            additonalHeaders);

            HttpWebResponse response     = wr as HttpWebResponse;
            FileWebResponse fileresponse = wr as FileWebResponse;

            if (response != null)
            {
                if (HttpStatusCode.OK == response.StatusCode ||
                    HttpExtendedStatusCode.IMUsed == (HttpExtendedStatusCode)response.StatusCode)
                {
                    responseResult = RequestResult.OK;
                    // stream will be disposed on response.Close():
                    Stream ret = MakeSeekableStream(response.GetResponseStream()); //GetDeflatedResponse(response);
                    response.Close();
                    return(ret);
                }
                if ((response.StatusCode == HttpStatusCode.MovedPermanently) ||
                    (response.StatusCode == HttpStatusCode.Moved))
                {
                    newAddress = HtmlHelper.ConvertToAbsoluteUrl(response.Headers["Location"], address, false);
                    address    = newAddress;
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsUnauthorized(response.StatusCode))
                {
                    //try with default credentials

                    useDefaultCred = true;
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsRedirect(response.StatusCode))
                {
                    address = HtmlHelper.ConvertToAbsoluteUrl(response.Headers["Location"], address, false);
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsAccessForbidden(response.StatusCode) &&
                         requestUri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ClientCertificateRequiredException();
                }
                else if (response.StatusCode == HttpStatusCode.Gone)
                {
                    throw new ResourceGoneException();
                }
                else
                {
                    string statusCode = response.StatusDescription;
                    if (String.IsNullOrEmpty(statusCode))
                    {
                        statusCode = response.StatusCode.ToString();
                    }
                    response.Close();
                    throw new WebException(String.Format("Request of '{0}' gets unexpected HTTP response: {1}",
                                                         requestUri, statusCode));
                }

                // unauthorized more than MaxRetries
                if (IsUnauthorized(response.StatusCode))
                {
                    response.Close();
                    throw new ResourceAuthorizationException();
                }

                //we got a moved, redirect more than MaxRetries
                string returnCode = response.StatusDescription;
                if (String.IsNullOrEmpty(returnCode))
                {
                    returnCode = response.StatusCode.ToString();
                }
                response.Close();
                throw new WebException(String.Format("Request of '{0}' gets repeated HTTP response: {1}", requestUri,
                                                     returnCode));
            }

            if (fileresponse != null)
            {
                responseResult = RequestResult.OK;
                // stream will be disposed on response.Close():
                Stream ret = MakeSeekableStream(fileresponse.GetResponseStream()); //GetDeflatedResponse(fileresponse);
                fileresponse.Close();
                return(ret);
            }
            throw new ApplicationException("no handler for WebResponse. Address: " + requestUri);
        }
Exemple #36
0
        /// <summary>
        /// post模拟表单提交(参数太长的时候用)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static String httpPost(String url, String postDataStr)
        {
            string          result   = "";
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;
            Stream          stream   = null;
            StreamReader    reader   = null;

            try
            {
                GC.Collect();    // 请求之前 做一次垃圾回收
                ServicePointManager.DefaultConnectionLimit = 20;
                // 打印 请求地址及参数
                LogHelper.Info("请求数据:" + url);
                request = (HttpWebRequest)WebRequest.Create(url);
                byte[] requestBytes = Encoding.ASCII.GetBytes(postDataStr);
                //request.Accept = "*/*";
                request.Method = "POST";
                //request.UserAgent = "Mozilla/5.0";
                request.CookieContainer = CookieEntity.cookie;
                request.KeepAlive       = false;                    // 保持短链接
                request.Timeout         = 1 * 60 * 1000;            // 1分钟,以防网络超时
                request.ContentType     = "application/x-www-form-urlencoded";
                Encoding encoding = Encoding.UTF8;                  //根据网站的编码自定义
                byte[]   postData = encoding.GetBytes(postDataStr); //postDataStr即为发送的数据,
                request.ContentLength = postData.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postData, 0, postData.Length);
                requestStream.Close();
                response            = (HttpWebResponse)request.GetResponse();
                CookieEntity.cookie = request.CookieContainer;
                stream = response.GetResponseStream();
                reader = new StreamReader(stream, Encoding.UTF8);
                result = reader.ReadToEnd().Trim();
                // 打印响应结果
                LogHelper.Info("响应结果:" + result);
                //if (result.Equals("远程服务器返回错误: (404) 未找到。"))
                //{
                //    throw new Exception(result);
                //}
            }
            catch (Exception e)
            {
                result = "{'state': false, 'message':'" + e.Message + "'}";
                LogHelper.Error(e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return(result);
        }
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <returns>The results of the command.</returns>
        public TwitterResponse<T> ExecuteCommand()
        {
            TwitterResponse<T> twitterResponse = new TwitterResponse<T>();

            if (this.OptionalProperties.UseSSL)
            {
                this.Uri = new Uri(this.Uri.AbsoluteUri.Replace("http://", "https://"));
            }

            // Loop through all of the custom attributes assigned to the command class
            foreach (Attribute attribute in this.GetType().GetCustomAttributes(false))
            {
                if (attribute is AuthorizedCommandAttribute)
                {
                    if (this.Tokens == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Tokens are required for the \"{0}\" command.", this.GetType()));
                    }

                    if (string.IsNullOrEmpty(this.Tokens.ConsumerKey) ||
                        string.IsNullOrEmpty(this.Tokens.ConsumerSecret) ||
                        string.IsNullOrEmpty(this.Tokens.AccessToken) ||
                        string.IsNullOrEmpty(this.Tokens.AccessTokenSecret))
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Token values cannot be null when executing the \"{0}\" command.", this.GetType()));
                    }
                }
                else if (attribute is RateLimitedAttribute)
                {
                    // Get the rate limiting status
                    if (TwitterRateLimitStatus.GetStatus(this.Tokens).ResponseObject.RemainingHits == 0)
                    {
                        throw new TwitterizerException("You are being rate limited.");
                    }
                }

            }

            // Prepare the query parameters
            Dictionary<string, object> queryParameters = new Dictionary<string, object>();
            foreach (KeyValuePair<string, object> item in this.RequestParameters)
            {
                queryParameters.Add(item.Key, item.Value);
            }

            // Declare the variable to be returned
            twitterResponse.ResponseObject = default(T);
            twitterResponse.RequestUrl = this.Uri.AbsoluteUri;
            RateLimiting rateLimiting;
            AccessLevel accessLevel;
            byte[] responseData;

            try
            {
				WebRequestBuilder requestBuilder = new WebRequestBuilder(this.Uri, this.Verb, this.Tokens) { Multipart = this.Multipart };

#if !SILVERLIGHT
                if (this.OptionalProperties != null)
                    requestBuilder.Proxy = this.OptionalProperties.Proxy;
#endif

                foreach (var item in queryParameters)
                {
                    requestBuilder.Parameters.Add(item.Key, item.Value);
                }

                HttpWebResponse response = requestBuilder.ExecuteRequest();

                if (response == null)
                {
                    twitterResponse.Result = RequestResult.Unknown;
                    return twitterResponse;
                }

                responseData = ConversionUtility.ReadStream(response.GetResponseStream());
                twitterResponse.Content = Encoding.UTF8.GetString(responseData, 0, responseData.Length);

                twitterResponse.RequestUrl = requestBuilder.RequestUri.AbsoluteUri;

#if !SILVERLIGHT
                // Parse the rate limiting HTTP Headers
                rateLimiting = ParseRateLimitHeaders(response.Headers);

                // Parse Access Level
                accessLevel = ParseAccessLevel(response.Headers);
#else
                rateLimiting = null;
                accessLevel = AccessLevel.Unknown;

#endif

                // Lookup the status code and set the status accordingly
                SetStatusCode(twitterResponse, response.StatusCode, rateLimiting);

                twitterResponse.RateLimiting = rateLimiting;
                twitterResponse.AccessLevel = accessLevel;
                response.Close();
            }
            catch (WebException wex)
            {
                if (new[]
                        {
#if !SILVERLIGHT
                            WebExceptionStatus.Timeout, 
                            WebExceptionStatus.ConnectionClosed,
#endif
                            WebExceptionStatus.ConnectFailure
                        }.Contains(wex.Status))
                {
                    twitterResponse.Result = RequestResult.ConnectionFailure;
                    twitterResponse.ErrorMessage = wex.Message;
                    return twitterResponse;
                }

                // The exception response should always be an HttpWebResponse, but we check for good measure.
                HttpWebResponse exceptionResponse = wex.Response as HttpWebResponse;

                if (exceptionResponse == null)
                {
                    throw;
                }

                responseData = ConversionUtility.ReadStream(exceptionResponse.GetResponseStream());
                twitterResponse.Content = Encoding.UTF8.GetString(responseData, 0, responseData.Length);

#if !SILVERLIGHT
                rateLimiting = ParseRateLimitHeaders(exceptionResponse.Headers);

                // Parse Access Level
                accessLevel = ParseAccessLevel(exceptionResponse.Headers);
#else
                rateLimiting = null;
                accessLevel = AccessLevel.Unknown;
#endif

                // Try to read the error message, if there is one.
                try
                {
                    TwitterErrorDetails errorDetails = SerializationHelper<TwitterErrorDetails>.Deserialize(responseData);
                    twitterResponse.ErrorMessage = errorDetails.ErrorMessage;
                }
                catch (Exception)
                {
                    // Occasionally, Twitter responds with XML error data even though we asked for json.
                    // This is that scenario. We will deal with it by doing nothing. It's up to the developer to deal with it.
                }

                // Lookup the status code and set the status accordingly
                SetStatusCode(twitterResponse, exceptionResponse.StatusCode, rateLimiting);

                twitterResponse.RateLimiting = rateLimiting;
                twitterResponse.AccessLevel = accessLevel;

                if (wex.Status == WebExceptionStatus.UnknownError)
                    throw;

                exceptionResponse.Close();

                return twitterResponse;
            }

            try
            {
                twitterResponse.ResponseObject = SerializationHelper<T>.Deserialize(responseData, this.DeserializationHandler);
            }
            catch (Newtonsoft.Json.JsonReaderException)
            {
                twitterResponse.ErrorMessage = "Unable to parse JSON";
                twitterResponse.Result = RequestResult.Unknown;
                return twitterResponse;
            }
            catch (Newtonsoft.Json.JsonSerializationException)
            {
                twitterResponse.ErrorMessage = "Unable to parse JSON";
                twitterResponse.Result = RequestResult.Unknown;
                return twitterResponse;
            }

            // Pass the current oauth tokens into the new object, so method calls from there will keep the authentication.
            twitterResponse.Tokens = this.Tokens;

            return twitterResponse;
        }
        public static string CertHelper(string filepath)
        {
            String       querys   = "";
            String       img_file = filepath;
            FileStream   fs       = new FileStream(img_file, FileMode.Open);
            BinaryReader br       = new BinaryReader(fs);

            byte[] contentBytes = br.ReadBytes(Convert.ToInt32(fs.Length));
            String base64       = System.Convert.ToBase64String(contentBytes);
            String bodys        = "{\"image\":\"" + base64 + "\""; //对图片内容进行Base64编码


            String          url          = host + path;
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/json; charset=UTF-8";
            // 设置并解析  格式
            String config = "{\\\"side\\\":\\\"face\\\"}";

            bodys = "{\"img\":\"" + base64 + "\"";
            if (config.Length < 0)
            {
                bodys += ",\"configure\" :\"" + config + "\"";
            }
            bodys += "}";


            httpRequest.ContentType = "application/json; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Console.WriteLine(httpResponse.StatusCode);
            Console.WriteLine(httpResponse.Method);
            Console.WriteLine(httpResponse.Headers);
            Stream       st       = httpResponse.GetResponseStream();
            StreamReader reader   = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string       analysis = reader.ReadToEnd();

            Console.WriteLine(reader.ReadToEnd());
            return(analysis);
        }
        public void GetTracks(int mode, string login, string artist, int pages, string path, bool filterByArtist, bool filterByPages)
        {
            procent = 0;
            if (String.IsNullOrEmpty(path)) // проверка на путь к файлу
            {
                path = "default.txt";
            }

            int totalPages = TotalPages(login, artist, filterByArtist);

            if (totalPages == 0) // если нет страниц
            {
                return;
            }
            procent = 5;
            if (filterByPages)
            {
                if (pages > totalPages) // проверка на не привышение страниц
                {
                    DialogResult f = MessageBox.Show("Количество страниц в фильтре больше, чем максимальное! Всего страниц - " + totalPages + ". Продолжить с максимальным количеством страниц?", "Непорядок :)", MessageBoxButtons.YesNo);
                    if (f == DialogResult.Yes)
                    {
                        pages = totalPages;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else
            {
                pages = totalPages;
            }

            //int totalPages = TotalPages(login, null);
            // int pages = 5;
            StreamWriter   wr         = new StreamWriter(path, false, Encoding.UTF8);
            string         parametres = String.Empty;
            string         s          = "";
            int            trackCount = 1;
            List <ToCFile> test       = new List <ToCFile>();

            for (int i = 1; i <= pages; i++)
            {
                if (chBSeparate.Checked)
                {
                    s += "____________________________________________\r\n";
                    s += "Page " + i + "\r\n";
                    s += "____________________________________________\r\n";
                }

                string requestText = String.Empty;
                if (filterByArtist)
                {
                    requestText += "http://ws.audioscrobbler.com/2.0/?method=library.gettracks&api_key=" + ApiKey + "&user="******"&page=" + i + "&artist=" + artist;
                }
                else
                {
                    requestText += "http://ws.audioscrobbler.com/2.0/?method=library.gettracks&api_key=" + ApiKey + "&user="******"&page=" + i;
                }
                // requestText += "http://ws.audioscrobbler.com/2.0/?method=library.gettracks&api_key=" + ApiKey + "&user="******"Mozilla/5.0";
                tracksRequest.Method      = "GET";                               // Указываем метод отправки данных скрипту, в случае с Post обязательно
                tracksRequest.ContentType = "application/x-www-form-urlencoded"; // основная строчка из-за которой не работало! (точнее, из-за того, что она была закомменчена). В случае с Post обязательна, видимо из-за её отсутствия неправильно кодировались данные
                // tracksRequest.Timeout = 5000; //

                HttpWebResponse tracksResponse = (HttpWebResponse)tracksRequest.GetResponse();
                string          tracksResult   = new StreamReader(tracksResponse.GetResponseStream(),
                                                                  Encoding.UTF8).ReadToEnd();

                if (!tracksResult.Contains("status=\"ok\"")) // проверяет, содержит ли строка эту подстроку, с учётом регистра
                {
                    throw new Exception("Произошла ошибка! Причина - " + tracksResult);
                }
                // MessageBox.Show(tracksResult);

                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.LoadXml(tracksResult);
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.Message);
                    // continue;
                }

                string tmp1 = "";
                foreach (XmlNode node in doc.SelectNodes("lfm/tracks/track")) // путь к значению по тегам
                {
                    if (mode == 1)
                    {
                        tmp1 = trackCount + ". ";
                        trackCount++;
                        // tmp1 += node.SelectNodes("artist/name")[0].InnerText; // теперь в текущем узле выбираем свои узлы (их по одному, поэтому берём нулевой)
                        tmp1 += node.SelectSingleNode("artist/name").InnerText;
                        tmp1 += " - " + node.SelectSingleNode("name").InnerText; // или так
                        tmp1 += " [" + node.SelectSingleNode("playcount").InnerText + " раз(а)]";
                        tmp1 += Environment.NewLine;
                        s    += tmp1;
                    }
                    else if (mode == 2)
                    {
                        test.Add(new ToCFile {
                            Artist    = node.SelectSingleNode("artist/name").InnerText,
                            PlayCount = Convert.ToInt32(node.SelectSingleNode("playcount").InnerText),
                            Track     = node.SelectSingleNode("name").InnerText
                        });
                    }
                }
                if (mode == 2)
                {
                    foreach (ToCFile g in test)
                    {
                        for (int q = 0; q < g.PlayCount; q++)
                        {
                            s += g.Artist + " - " + g.Track + "\r\n";
                        }
                    }
                    test.Clear(); // чистим список, чтобы по 2 раза не забивать песни
                }
                procent = (i + 1) * (100 / pages);
            }


            wr.Write(s);
            wr.Close();
            MessageBox.Show("Готово!");
            procent = 100;
            if (chbAutoOpen.Checked)
            {
                Process.Start(path);
            }
        }
        private string GetWebDocument(string url)
        {
            HttpWebResponse result = null;
            StringBuilder sb = new StringBuilder();
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

                string lang = Request.Headers["Accept-Language"];
                req.Headers["Accept-Language"] = lang;

                string username = ConfigurationManager.AppSettings["AWStats.Username"];
                if (username != null && username != "")
                {
                    string password = ConfigurationManager.AppSettings["AWStats.Password"];
                    string domain = null;
                    int sepIdx = username.IndexOf("\\");
                    if (sepIdx != -1)
                    {
                        domain = username.Substring(0, sepIdx);
                        username = username.Substring(sepIdx + 1);
                    }

                    req.Credentials = new NetworkCredential(username, password, domain);
                }
                else
                {
                    req.Credentials = CredentialCache.DefaultNetworkCredentials;
                }

                result = (HttpWebResponse)req.GetResponse();
                Stream ReceiveStream = result.GetResponseStream();
                string respEnc = !String.IsNullOrEmpty(result.ContentEncoding) ? result.ContentEncoding : "utf-8";
                Encoding encode = System.Text.Encoding.GetEncoding(respEnc);

                StreamReader sr = new StreamReader(ReceiveStream, encode);

                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    sb.Append(str);
                    count = sr.Read(read, 0, 256);
                }
            }
            catch (WebException ex)
            {
                Response.Write("Error while opening '" + url + "': " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
            finally
            {
                if (result != null)
                {
                    result.Close();
                }
            }

            return sb.ToString();
        }
Exemple #41
0
        public static RunResult Run(string[] args)
        {
            var result  = new RunResult();
            var options = Parser.ParseArgs(args);

            HttpWebResponse response = null;

            var client = new Client();

            try
            {
                response = client.GetResponse(options);


                if (options.CheckStatus)
                {
                    result.ExitCode = GetExitStatus(response.StatusCode, options.AllowRedirects);
                }

                if (options.IsVerbose)
                {
                    result.OutputMessage = Output.Write(options, client.Request, client.RequestBody);
                }

                var receivedStream = response.GetResponseStream();

                if (receivedStream != null && receivedStream.CanRead)
                {
                    var encode     = Encoding.GetEncoding(!string.IsNullOrEmpty(response.ContentEncoding) ? response.ContentEncoding : "utf-8");
                    var readStream = new StreamReader(receivedStream, encode);
                    result.ResponseBody = readStream.ReadToEnd();
                    readStream.Close();
                }
                result.ResponseCode = (int)response.StatusCode;
            }
            catch (WebException web)
            {
                if (web.Response != null)
                {
                    response            = (HttpWebResponse)web.Response;
                    result.ResponseCode = (int)response.StatusCode;
                    result.ExitCode     = GetExitStatus(response.StatusCode, options.AllowRedirects);
                    result.ErrorMessage = web.Message;
                }
                else
                {
                    result.ExitCode     = Consts.EXIT.ERROR;
                    result.ErrorMessage = web.Status + " " + web.Message;
                }
            }
            catch (Exception ex)
            {
                result.ExitCode     = Consts.EXIT.ERROR;
                result.ErrorMessage = ex.Message;
            }


            result.OutputMessage += Output.Write(options, result, response);

            if (response != null)
            {
                response.Close();
            }
            return(result);
        }
Exemple #42
0
        private void GetChummerVersion()
        {
            if (_blnUnBlocked)
            {
                string strUpdateLocation = "https://api.github.com/repos/chummer5a/chummer5a/releases/latest";
                if (_blnPreferNightly)
                {
                    strUpdateLocation = "https://api.github.com/repos/chummer5a/chummer5a/releases";
                }
                HttpWebRequest request = WebRequest.Create(strUpdateLocation) as HttpWebRequest;
                if (request == null)
                {
                    return;
                }
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.Accept    = "application/json";
                // Get the response.

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                // Get the stream containing content returned by the server.
                Stream dataStream = response?.GetResponseStream();
                if (dataStream == null)
                {
                    return;
                }
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.

                string   responseFromServer = reader.ReadToEnd();
                string[] stringSeparators   = new string[] { "," };
                string[] result             = responseFromServer.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                bool blnFoundTag     = false;
                bool blnFoundArchive = false;
                foreach (string line in result)
                {
                    if (!blnFoundTag && line.Contains("tag_name"))
                    {
                        _strLatestVersion = line.Split(':')[1];
                        LatestVersion     = _strLatestVersion.Split('}')[0].FastEscape('\"');
                        blnFoundTag       = true;
                        if (blnFoundArchive)
                        {
                            break;
                        }
                    }
                    if (!blnFoundArchive && line.Contains("browser_download_url"))
                    {
                        _strDownloadFile = line.Split(':')[2];
                        _strDownloadFile = _strDownloadFile.Substring(2);
                        _strDownloadFile = _strDownloadFile.Split('}')[0].FastEscape('\"');
                        _strDownloadFile = "https://" + _strDownloadFile;
                        blnFoundArchive  = true;
                        if (blnFoundTag)
                        {
                            break;
                        }
                    }
                }
                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();
            }
            else
            {
                LatestVersion = LanguageManager.GetString("String_No_Update_Found");
            }
            DoVersionTextUpdate();
        }
Exemple #43
0
        /// <summary>
        /// Get every WebPage.Internal on a web site (or part of a web site) visiting all internal links just once
        /// plus every external page (or other Url) linked to the web site as a WebPage.External
        /// </summary>
        /// <remarks>
        /// Use .OfType WebPage.Internal to get just the internal ones if that's what you want
        /// </remarks>
        public static IEnumerable <WebPage> GetAllPagesUnder(Uri urlRoot)
        {
            int safetyCount = 0;

            var queue       = new Queue <Uri>();
            var allSiteUrls = new HashSet <Uri>();

            queue.Enqueue(urlRoot);
            allSiteUrls.Add(urlRoot);

            while (queue.Count > 0 && safetyCount++ < 5)
            {
                Uri url = queue.Dequeue();

                HttpWebRequest oReq = (HttpWebRequest)WebRequest.Create(url);
                oReq.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";

                HttpWebResponse resp = (HttpWebResponse)oReq.GetResponse();

                WebPage result;

                if (resp.ContentType.StartsWith("text/html", StringComparison.InvariantCultureIgnoreCase))
                {
                    HtmlDocument doc = new HtmlDocument();
                    try
                    {
                        var resultStream = resp.GetResponseStream();
                        doc.Load(resultStream); // The HtmlAgilityPack
                        result = new Internal()
                        {
                            Url = url, HtmlDocument = doc
                        };
                    }
                    catch (System.Net.WebException ex)
                    {
                        result = new WebPage.Error()
                        {
                            Url = url, Exception = ex
                        };
                    }
                    catch (Exception ex)
                    {
                        ex.Data.Add("Url", url);    // Annotate the exception with the Url
                        throw;
                    }

                    // Success, hand off the page
                    yield return(new WebPage.Internal()
                    {
                        Url = url, HtmlDocument = doc
                    });


                    // And and now queue up all the links on this page
                    foreach (HtmlNode link in doc.DocumentNode.SelectNodes(@"//a[@href]"))
                    {
                        HtmlAttribute att = link.Attributes["href"];
                        if (att == null)
                        {
                            continue;
                        }
                        string href = att.Value;
                        if (href.StartsWith("javascript", StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;                                                                                  // ignore javascript on buttons using a tags
                        }
                        Uri urlNext = new Uri(href, UriKind.RelativeOrAbsolute);

                        // Make it absolute if it's relative
                        if (!urlNext.IsAbsoluteUri)
                        {
                            urlNext = new Uri(urlRoot, urlNext);
                        }

                        if (!allSiteUrls.Contains(urlNext))
                        {
                            allSiteUrls.Add(urlNext);               // keep track of every page we've handed off

                            if (urlRoot.IsBaseOf(urlNext))
                            {
                                queue.Enqueue(urlNext);
                            }
                            else
                            {
                                yield return(new WebPage.External()
                                {
                                    Url = urlNext
                                });
                            }
                        }
                    }
                }
            }
        }
		HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
		{
			var response = new HttpResponseMessage (wr.StatusCode);
			response.RequestMessage = requestMessage;
			response.ReasonPhrase = wr.StatusDescription;
			response.Content = new StreamContent (wr.GetResponseStream (), cancellationToken);

			var headers = wr.Headers;
			for (int i = 0; i < headers.Count; ++i) {
				var key = headers.GetKey(i);
				var value = headers.GetValues (i);

				HttpHeaders item_headers;
				if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content)
					item_headers = response.Content.Headers;
				else
					item_headers = response.Headers;
					
				item_headers.TryAddWithoutValidation (key, value);
			}

			requestMessage.RequestUri = wr.ResponseUri;

			return response;
		}
Exemple #45
0
    public WebReq(string _siteName, getPost _opType, Connection _connection, bool _silent = true, string _strBuffer = "")
    {
        HttpWebRequest localRequest;
        string requestMethod;

        hostSiteName = _siteName;
        currentRequest = _opType;
        formConnection = _connection;

        switch (currentRequest)
        {
            case getPost.get:
                webRequestGET = (HttpWebRequest)WebRequest.Create(_siteName);
                requestMethod = "GET";
                localRequest = webRequestGET;
                break;
            case getPost.post:
                webRequestPOST = (HttpWebRequest)WebRequest.Create(_siteName);
                requestMethod = "POST";
                localRequest = webRequestPOST;
                break;
            default:
                localRequest = null;
                requestMethod = "";
                break;
        }
        localRequest.ContentType = "application/x-www-form-urlencoded";
        localRequest.Method = requestMethod;
        addCookie(localRequest, formConnection);

        if (_strBuffer.Length != 0 && currentRequest == getPost.post)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(_strBuffer);
            localRequest.ContentLength = buffer.Length;
            Stream PostData = localRequest.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
        }
        webResponse = (HttpWebResponse)localRequest.GetResponse();
        Answer = webResponse.GetResponseStream();
    }
Exemple #46
0
 private string ReadResponse(HttpWebResponse response)
 {
     StreamReader responseReader = new StreamReader(response.GetResponseStream());
     return responseReader.ReadToEnd();
 }
Exemple #47
0
        /**
         * Http Get Request
         *
         * @param List<string> request of URL directories.
         * @return List<object> from JSON response.
         */
        private bool _request(List <string> url_components, ResponseType type)
        {
            List <object> result = new List <object>();
            StringBuilder url    = new StringBuilder();

            // Add Origin To The Request
            url.Append(this.ORIGIN);

            // Generate URL with UTF-8 Encoding
            foreach (string url_bit in url_components)
            {
                url.Append("/");
                url.Append(_encodeURIcomponent(url_bit));
            }

            if (type == ResponseType.Presence || type == ResponseType.Subscribe)
            {
                url.Append("?uuid=");
                url.Append(this.sessionUUID);
            }

            if (type == ResponseType.DetailedHistory)
            {
                url.Append(parameters);
            }

            // Temporary fail if string too long
            if (url.Length > this.LIMIT)
            {
                result.Add(0);
                result.Add("Message Too Long.");
                // return result;
            }

            Uri requestUri = new Uri(url.ToString());

            // Force canonical path and query
            string    paq            = requestUri.PathAndQuery;
            FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
            ulong     flags          = (ulong)flagsFieldInfo.GetValue(requestUri);

            flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
            flagsFieldInfo.SetValue(requestUri, flags);

            // Create Request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            try
            {
                // Make request with the following inline Asynchronous callback
                IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback((asynchronousResult) =>
                {
                    HttpWebRequest aRequest   = (HttpWebRequest)asynchronousResult.AsyncState;
                    HttpWebResponse aResponse = (HttpWebResponse)aRequest.EndGetResponse(asynchronousResult);
                    using (StreamReader streamReader = new StreamReader(aResponse.GetResponseStream()))
                    {
                        // Deserialize the result
                        string jsonString = streamReader.ReadToEnd();
                        result            = DeserializeToListOfObject(jsonString);

                        JavaScriptSerializer jS = new JavaScriptSerializer();
                        result = (List <object>)jS.Deserialize <List <object> >(jsonString);
                        var resultOccupancy = jS.DeserializeObject(jsonString);

                        if ((result.Count != 0) && (type != ResponseType.DetailedHistory))
                        {
                            if (result[0] is object[])
                            {
                                foreach (object message in (object[])result[0])
                                {
                                    this.ReturnMessage = message;
                                }
                            }
                        }

                        switch (type)
                        {
                        case ResponseType.Publish:
                            result.Add(url_components[4]);
                            Publish = result;
                            break;

                        case ResponseType.History:
                            if (this.CIPHER_KEY.Length > 0)
                            {
                                List <object> historyDecrypted = new List <object>();
                                PubnubCrypto aes = new PubnubCrypto(this.CIPHER_KEY);
                                foreach (object message in result)
                                {
                                    historyDecrypted.Add(aes.decrypt(message.ToString()));
                                }
                                History = historyDecrypted;
                            }
                            else
                            {
                                History = result;
                            }
                            break;

                        case ResponseType.DetailedHistory:
                            if (this.CIPHER_KEY.Length > 0)
                            {
                                List <object> historyDecrypted = new List <object>();
                                PubnubCrypto aes = new PubnubCrypto(this.CIPHER_KEY);
                                foreach (object message in (object[])result[0])
                                {
                                    historyDecrypted.Add(aes.decrypt(message.ToString()));
                                }
                                DetailedHistory = historyDecrypted;
                            }
                            else
                            {
                                DetailedHistory = (object[])(result[0]);
                            }
                            break;

                        case ResponseType.Here_Now:
                            Dictionary <string, object> dic = (Dictionary <string, object>)resultOccupancy;
                            List <object> presented         = new List <object>();
                            presented.Add(dic);
                            Here_Now = (List <object>)presented;
                            break;

                        case ResponseType.Time:
                            Time = result;
                            break;

                        case ResponseType.Subscribe:
                            result.Add(url_components[2]);
                            Subscribe = result;
                            break;

                        case ResponseType.Presence:
                            result.Add(url_components[2]);
                            Presence = result;
                            break;

                        default:
                            break;
                        }
                    }
                }), request

                                                                    );
                //asyncResult.AsyncWaitHandle.WaitOne();
                return(true);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(false);
            }
        }
        /// <summary>
        /// This method execute web request to check server status.
        /// </summary>
        /// <param name="request">request string to execute.</param>
        /// <returns>Response stream</returns>
        public Stream ExecuteWebRequest(string request, ref int statusCode, ref string statusDescription, ref string errorMessage)
        {
            Stream responseStream = null;

            try
            {
                statusCode        = 1000;
                statusDescription = "Unknown";
                errorMessage      = "Unknown error has occured.";

                HttpWebRequest httpRequest = WebRequest.Create(request) as HttpWebRequest;

                HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;
                statusCode        = Convert.ToInt32(response.StatusCode);
                statusDescription = response.StatusDescription;
                errorMessage      = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    statusCode        = Convert.ToInt32(response.StatusCode);
                    statusDescription = response.StatusDescription;
                    errorMessage      = string.Empty;

                    System.Diagnostics.Debug.WriteLine("Http Request Error:  StatusCode: " +
                                                       response.StatusCode + "Description : " + response.StatusDescription);

                    HelperMethods.AddLogs(string.Format("ExecuteWebRequest: Http Request Error:  StatusCode = {0}, Description = {1}", response.StatusCode, response.StatusDescription));
                }

                // Get response stream
                responseStream = response.GetResponseStream();

                // Dispose the response stream.
                //responseStream.Dispose();
            }
            catch (WebException webException)
            {
                try
                {
                    HttpWebResponse webResponse = webException.Response as HttpWebResponse;
                    if (webResponse != null)
                    {
                        statusCode        = Convert.ToInt32(webResponse.StatusCode);
                        statusDescription = webResponse.StatusDescription;

                        Stream       stream           = webResponse.GetResponseStream();
                        StreamReader streamReader     = new StreamReader(stream);
                        string       textErrorMessage = streamReader.ReadToEnd();
                        errorMessage = textErrorMessage;
                    }
                    else
                    {
                        statusCode        = Convert.ToInt32(webException.Status);
                        statusDescription = "WebException Status Messgae =>" + webException.Message;
                        errorMessage      = webException.StackTrace;
                    }
                }
                catch (Exception ex)
                {
                    statusCode        = 1008;
                    statusDescription = "ExceptionOccurred";
                    errorMessage      = ex.Message;
                    HelperMethods.AddLogs(string.Format("ExecuteWebRequest: Exception occurred when handling WebException Exception = {0}", ex.Message));
                }
            }
            catch (Exception ex)
            {
                HelperMethods.AddLogs(string.Format("ExecuteWebRequest: Exception = {0}", ex.Message));
                statusCode        = 1008;
                statusDescription = "ExceptionOccurred";
                errorMessage      = ex.Message;
            }

            return(responseStream);
        }
Exemple #49
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="encode"></param>
        /// <param name="timeout"></param>
        /// <param name="headers"></param>
        /// <param name="datas"></param>
        /// <param name="origDatas"></param>
        /// <param name="responseHeader"></param>
        /// <param name="cookies"></param>
        /// <returns></returns>
        public static string GetCtx(string url, RequestMethod method, Encoding encode, int?timeout, Dictionary <string, string> headers, Dictionary <string, string> datas, string origDatas, out WebHeaderCollection responseHeader, out CookieCollection cookies)
        {
            cookies        = null;
            responseHeader = null;

            if (string.IsNullOrWhiteSpace(url))
            {
                return("");
            }

            if (!urlCheckReg.Match(url).Success)
            {
                url = "http://" + url;
            }

            //method = method.ToUpper();
            if (method == RequestMethod.GET)
            {
                url = GetRequestUrl(url, datas, encode);
            }

            if (url.StartsWith("https", true, null))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            if (encode == null)
            {
                encode = Encoding.UTF8;
            }

            try {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                if (timeout != null && timeout > 0)
                {
                    req.Timeout = (int)timeout;
                }

                //WebProxy proxy = new WebProxy("172.18.20.1", 8080);
                //proxy.Credentials = new NetworkCredential("gruan", "xxx", "CN3");
                //req.Proxy = proxy;


                req.Method          = method.ToString();
                req.CookieContainer = new CookieContainer();
                SetRequestHeaders(req, headers);
                if (method == RequestMethod.POST)
                {
                    SetPostData(req, datas, origDatas, encode);
                }


                HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
                cookies        = rep.Cookies;
                responseHeader = rep.Headers;
                StreamReader sr  = new StreamReader(rep.GetResponseStream(), encode);
                string       ctx = sr.ReadToEnd();
                sr.Close();
                rep.Close();
                return(ctx);
            } catch (Exception ex) {
                return(ex.Message);
            }
        }
		public static ICrossDomainPolicy BuildFlashPolicy (HttpWebResponse response)
		{
			ICrossDomainPolicy policy = null;
			if ((response.StatusCode == HttpStatusCode.OK) && CheckContentType (response.ContentType)) {
				try {
					policy = FlashCrossDomainPolicy.FromStream (response.GetResponseStream ());
				} catch (Exception ex) {
					Console.WriteLine (String.Format ("CrossDomainAccessManager caught an exception while reading {0}: {1}", 
						response.ResponseUri, ex));
					// and ignore.
				}
				if (policy != null) {
					// see DRT# 864 and 865
					string site_control = response.InternalHeaders ["X-Permitted-Cross-Domain-Policies"];
					if (!String.IsNullOrEmpty (site_control))
						(policy as FlashCrossDomainPolicy).SiteControl = site_control;
				}
			}

			// the flash policy was the last chance, keep a NoAccess into the cache
			if (policy == null)
				policy = no_access_policy;

			AddPolicy (response.ResponseUri, policy);
			return policy;
		}
Exemple #51
0
 /// <summary>
 /// 接收网络的响应
 /// </summary>
 /// <param name="request"></param>
 /// <param name="response">可能产生异常</param>
 private static void WaitForResponse(HttpWebRequest request,HttpWebResponse response)
 {
     using(response=(HttpWebResponse )request .GetResponse())
     {
         if (response.StatusCode == HttpStatusCode.OK)
         {
             #region 响应成功
             using (Stream dataStream = response.GetResponseStream())
             {
                 using (StreamReader reader = new StreamReader(dataStream))
                 {
                     string responseBody = reader.ReadToEnd();
                     try
                     {
                         OnObtainData(responseBody);
                     }
                     catch (Exception ex)
                     {
                         print("网络出现异常,异常信息:" + ex.Message);
                     }
                 }
             }
             #endregion
         }
     }
 }