public TaskStatus Handle(IHttpProxy httpHandler)
        {
            using (Log log = new Log("美团.CreateOrder", false))
            {
                httpHandler.ResponseContentType = "application/json";
                var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();
                log.LogJson(forms);
                try
                {
                    if (forms.Count > 0)
                    {
                        //验证sign
                        var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                        if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                        {
                            throw new Exception("签名验证失败");
                        }

                        handleContent(forms["order"], int.Parse(forms["ePoiId"]));
                    }
                }
                catch (Exception ex)
                {
                    using (Log logErr = new Log("美团CreateOrderCallback解析错误"))
                    {
                        logErr.Log(ex.ToString());
                    }
                    throw ex;
                }
                httpHandler.ResponseWrite("{\"data\":\"OK\"}");

                return(TaskStatus.Completed);
            }
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        public bool TryRotate(IHttpProxy currentProxy, IReadOnlyCollection <IHttpProxyState> aliveProxies,
                              out Guid newProxyId)
        {
            if (currentProxy != null)
            {
                var position = Array.IndexOf(aliveProxies.Select(a => a.Proxy).ToArray(), currentProxy);
                if (position != -1 && position + 1 != aliveProxies.Count)
                {
                    var nextFreeProxy = aliveProxies
                                        .Skip(position + 1)
                                        .FirstOrDefault(a => !a.IsProxyAcquired);

                    if (nextFreeProxy != null)
                    {
                        newProxyId = nextFreeProxy.Proxy.Id;
                        return(true);
                    }
                }
            }

            var freeProxy = aliveProxies.FirstOrDefault(s => !s.IsProxyAcquired);

            if (freeProxy != null)
            {
                newProxyId = freeProxy.Proxy.Id;
            }

            return(freeProxy != null);
        }
Exemplo n.º 3
0
        public CefBrowserProvider(IHttpProxy proxy, IShellContextService shellContextService, ISettingsManager settings)
        {
            this.proxy = proxy;
            this.shellContextService = shellContextService;

            clearCacheOnStartup = settings.Register("cef.clear_cache_on_startup", false);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Creates a connection that will forward the request to the specified host and port
 /// </summary>
 /// <param name="fwHost"></param>
 /// <param name="fwPort"></param>
 /// <param name="client"></param>
 /// <param name="isSecure"></param>
 /// <param name="dataStore"></param>
 /// <param name="networkSettings"></param>
 /// <param name="parentProxy"></param>
 public TrackingReverseProxyConnection(TcpClient client, bool isSecure, ITrafficDataAccessor dataStore, INetworkSettings networkSettings, IHttpProxy parentProxy)
     : base(client, isSecure, dataStore, Resources.TrackingReverseProxyDescription, networkSettings, false)
 {
     _dataStore       = dataStore;
     _parentProxy     = parentProxy;
     _networkSettings = networkSettings;
 }
Exemplo n.º 5
0
        private void ReloadProxyClick(object sender, EventArgs e)
        {
            IHttpProxy proxy = GetCurrentProxy();

            if (proxy.IsListening)
            {
                proxy.Stop();
            }
            string currentSelection = _availableProxies.Text;

            if (_proxyFactory.AvailableTypes.Contains(currentSelection))
            {
                proxy = _proxyFactory.MakeProxy(currentSelection);
            }
            else
            {
                foreach (IHttpProxyFactory factory in TrafficViewer.Instance.HttpProxyFactoryList)
                {
                    if (factory.Name.Equals(currentSelection))
                    {
                        HttpServerConsole.Instance.WriteLine(LogMessageType.Information,
                                                             "Re-creating proxy: '{0}'", factory.Name);
                        proxy = factory.MakeProxyServer(TrafficViewerOptions.Instance.TrafficServerIp,
                                                        TrafficViewerOptions.Instance.TrafficServerPort,
                                                        TrafficViewerOptions.Instance.TrafficServerPortSecure,
                                                        TrafficViewer.Instance.TrafficViewerFile);
                    }
                }
            }
            _initializedProxies[currentSelection] = proxy;
        }
Exemplo n.º 6
0
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            using (Log log = new Log("CailutongGateway.Notify_RequestHandler"))
            {
                try
                {
                    string json = httpProxy.ReadRequestBody();
                    log.Log(json);

                    SortedDictionary <string, object> dict = Newtonsoft.Json.JsonConvert.DeserializeObject <SortedDictionary <string, object> >(json);
                    string outTradeNo = (string)dict["outTradeNo"];
                    var    config     = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.CailutongBTC, outTradeNo));

                    if (Cailutong_Helper.Sign(dict, config.Secret) != (string)dict["sign"])
                    {
                        throw new Exception("校验失败");
                    }

                    var status = Convert.ToInt32(dict["status"]);

                    if (status == 2)
                    {
                        PayFactory.OnPaySuccessed(outTradeNo, Convert.ToDouble(dict["payedAmount"]), null, json);
                    }

                    httpProxy.ResponseWrite("{\"status\":\"success\"}");
                }
                catch (Exception ex)
                {
                    log.Log(ex.ToString());
                }
            }
            return(TaskStatus.Completed);
        }
Exemplo n.º 7
0
        public async Task <bool> IsAliveAsync(IHttpProxy proxy, CancellationToken cancellation)
        {
            using (var ping = new Ping())
            {
                var isOk = false;

                try
                {
                    var uriBuilder = new UriBuilder(proxy.Address);
                    if (!proxy.Address.IsDefaultPort)
                    {
                        uriBuilder.Port = -1;
                    }

                    var reply = await ping.SendPingAsync(uriBuilder.Uri.Host, 2000);

                    isOk = reply != null && reply.Status == IPStatus.Success;
                }
                catch
                {
                    isOk = false;
                }
                finally
                {
                    _logger.LogInformation($"Ping health check '{proxy.Address}': {(isOk ? "passed" : "failed")}");
                }

                return(isOk);
            }
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            var json = httpProxy.Form["request"];

            try
            {
                using (CLog log = new CLog("IPaysoonNotify Notify"))
                {
                    log.Log(json);
                    var result = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    if (result["resultCode"].ToString() == "0000" && result["statusId"].ToString() == "14")
                    {
                        var tradid = result["merchantGenCode"].ToString();
                        var charge = Convert.ToDouble(result["charge"].ToString()) / 100.0;
                        var amount = Convert.ToDouble(result["amount"].ToString()) / 100.0;
                        log.Log("tradid:{0} charge:{1} amount:{2}", tradid, charge, amount);
                        log.Log("excute OnPaySuccessed");
                        PayFactory.OnPaySuccessed(tradid, amount - charge, null, json);
                    }
                    httpProxy.ResponseWrite("SUCCESS");
                }
            }
            catch (Exception ex)
            {
                using (CLog log = new CLog("IPaysoon Notify error "))
                {
                    log.Log(ex.ToString());
                }
            }
            return(TaskStatus.Completed);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Proxies the incoming request to the destination server, and the response back to the client.
 /// </summary>
 /// <param name="context">The HttpContent to proxy from.</param>
 /// <param name="destinationPrefix">The url prefix for where to proxy the request to.</param>
 /// <param name="httpClient">The HTTP client used to send the proxy request.</param>
 public static Task ProxyAsync(
     this IHttpProxy proxy,
     HttpContext context,
     string destinationPrefix,
     HttpMessageInvoker httpClient)
 {
     return(proxy.ProxyAsync(context, destinationPrefix, httpClient, requestOptions: default, HttpTransformer.Default));
Exemplo n.º 10
0
        private static string Get(string url, string encoding, IHttpProxy proxy)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.Timeout = 10 * 1000;
            request.Proxy = GetWebProxy(proxy);

            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                Log.Error(e);
                return string.Empty;
            }

            return string.Empty;
        }
Exemplo n.º 11
0
Arquivo: Http.cs Projeto: xieby/Wox
        /// <exception cref="WebException">Can't get response from http get </exception>
        public static async Task<string> Get([NotNull] string url, IHttpProxy proxy, string encoding = "UTF-8")
        {

            HttpWebRequest request = WebRequest.CreateHttp(url);
            request.Method = "GET";
            request.Timeout = 10 * 1000;
            request.Proxy = WebProxy(proxy);
            request.UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
            var response = await request.GetResponseAsync() as HttpWebResponse;
            if (response != null)
            {
                var stream = response.GetResponseStream();
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                    {
                        return await reader.ReadToEndAsync();
                    }
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }
Exemplo n.º 12
0
        /// <exception cref="WebException">Can't get response from http get </exception>
        public static async Task <string> Get([NotNull] string url, IHttpProxy proxy, string encoding = "UTF-8")
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);

            request.Method    = "GET";
            request.Timeout   = 10 * 1000;
            request.Proxy     = WebProxy(proxy);
            request.UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
            var response = await request.GetResponseAsync() as HttpWebResponse;

            if (response != null)
            {
                var stream = response.GetResponseStream();
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                    {
                        return(await reader.ReadToEndAsync());
                    }
                }
                else
                {
                    return(string.Empty);
                }
            }
            else
            {
                return(string.Empty);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHttpProxy httpProxy)
        {
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            // Copy all request headers except Host
            var transformer    = new CustomTransformer(); // or HttpTransformer.Default;
            var requestOptions = new RequestProxyOptions(TimeSpan.FromSeconds(100), null);

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    await httpProxy.ProxyAsync(httpContext, "https://localhost:10000/", httpClient, requestOptions, transformer);
                    var errorFeature = httpContext.Features.Get <IProxyErrorFeature>();
                    if (errorFeature != null)
                    {
                        var error     = errorFeature.Error;
                        var exception = errorFeature.Exception;
                    }
                });
            });
        }
Exemplo n.º 14
0
        /// <exception cref="WebException">Can't download file </exception>
        public static void Download([NotNull] string url, [NotNull] string filePath, IHttpProxy proxy)
        {
            var client = new WebClient {
                Proxy = WebProxy(proxy)
            };

            client.DownloadFile(url, filePath);
        }
Exemplo n.º 15
0
 public HeaderIntegrationProxyRouter(IHttpProxy httpProxy,
                                     ProxyRouteCollection proxyRouteCollection,
                                     ILogger <HeaderIntegrationProxyRouter> logger)
 {
     this.HttpProxy            = httpProxy;
     this.ProxyRouteCollection = proxyRouteCollection;
     this.Logger = logger;
 }
Exemplo n.º 16
0
 /// <summary>
 /// Proxies the incoming request to the destination server, and the response back to the client.
 /// </summary>
 /// <param name="context">The HttpContent to proxy from.</param>
 /// <param name="destinationPrefix">The url prefix for where to proxy the request to.</param>
 /// <param name="httpClient">The HTTP client used to send the proxy request.</param>
 /// <returns>The result of the request proxying to the destination.</returns>
 public static ValueTask <ProxyError> ProxyAsync(
     this IHttpProxy proxy,
     HttpContext context,
     string destinationPrefix,
     HttpMessageInvoker httpClient)
 {
     return(proxy.ProxyAsync(context, destinationPrefix, httpClient, RequestProxyConfig.Empty, HttpTransformer.Default));
 }
Exemplo n.º 17
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpProxy httpProxy)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    var mocks  = httpContext.RequestServices.GetRequiredService <Mocks>();
                    var logger = httpContext.RequestServices.GetRequiredService <ILogger <Startup> >();

                    var match = mocks.Files.Values
                                .SelectMany(v => v.Log.Entries)
                                .Where(e => new Uri(e.Request.Url).AbsolutePath.ToLower() == httpContext.Request.Path.Value.ToLower())
                                .FirstOrDefault();

                    // Found match in HAR file mock api use HAR response
                    if (match != null)
                    {
                        logger.LogInformation($"Mocking API {new Uri(match.Request.Url).AbsolutePath}");

                        foreach (var header in match.Response.Headers)
                        {
                            if (!new[] { "content-length", "content-encoding" }.Any(h => header.Name.ToLower() == h))
                            {
                                httpContext.Response.Headers.TryAdd(header.Name, header.Value);
                            }
                        }

                        httpContext.Response.StatusCode = match.Response.Status;
                        await httpContext.Response.WriteAsync(match.Response.Content.Text);
                        return;
                    }

                    // No match found, forward request to original api
                    await httpProxy.ProxyAsync(httpContext, _config.GetValue <string>("Api:Url"), httpClient);

                    // Log errors from forwarded request
                    var errorFeature = httpContext.Features.Get <IProxyErrorFeature>();
                    if (errorFeature != null)
                    {
                        logger.LogError(errorFeature.Exception, $"{errorFeature.Error}");
                    }
                });
            });
        }
Exemplo n.º 18
0
        private void AvailableProxiesSelectedIndexChanged(object sender, EventArgs e)
        {
            IHttpProxy proxy = GetCurrentProxy();

            if (proxy != null)
            {
                UpdateStartStopButtonStatus(proxy);
            }
        }
 public BasicAuthenticationHandler(IOptionsMonitor <BasicAuthenticationOptions> options,
                                   ILoggerFactory logger,
                                   UrlEncoder encoder,
                                   ISystemClock clock,
                                   IHttpProxy httpProxy)
     : base(options, logger, encoder, clock)
 {
     _httpProxy = httpProxy;
 }
Exemplo n.º 20
0
        public static string Post(string url, string jsonData, IHttpProxy proxy)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(string.Empty);
            }

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

            request.Method      = "POST";
            request.ContentType = "text/json";
            request.Timeout     = 10 * 1000;
            if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
            {
                if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port);
                }
                else
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port)
                    {
                        Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
                    };
                }
            }
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(jsonData);
                streamWriter.Flush();
                streamWriter.Close();
            }

            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                        {
                            return(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                Logger.Log.Error(e);
                return(string.Empty);
            }

            return(string.Empty);
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpProxy httpProxy, WPMessageInvokerFactory messageInvoker, WPProxySettings settings)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseStaticFiles();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();


            app.Use(next => context =>
            {
                // Force https scheme (since request inside a docker container may appear to be http)
                context.Request.Scheme = "https";
                return(next(context));
            });

            var transformer    = new WPRequestTransformer(); // or HttpTransformer.Default;
            var requestOptions = new RequestProxyOptions {
                Timeout       = TimeSpan.FromSeconds(100),
                Version       = new Version(1, 1), // Not all servers support HTTP 2
                VersionPolicy = HttpVersionPolicy.RequestVersionOrHigher
            };

            app.UseEndpoints(endpoints =>
            {
                // Dont't authenticate manifest.json
                endpoints.Map("/manifest.json", async httpContext => //
                {
                    var siteSettings = settings.GetForHost(httpContext.Request.Host.ToString());
                    await httpProxy.ProxyAsync(httpContext, siteSettings.SourceAddress, messageInvoker.Create(), requestOptions, transformer);
                });

                endpoints.Map("/{**catch-all}", async httpContext => //
                {
                    var siteSettings = settings.GetForHost(httpContext.Request.Host.ToString());
                    await httpProxy.ProxyAsync(httpContext, siteSettings.SourceAddress, messageInvoker.Create(), requestOptions, transformer);

                    var errorFeature = httpContext.Features.Get <IProxyErrorFeature>();
                    if (errorFeature != null)
                    {
                        var error     = errorFeature.Error;
                        var exception = errorFeature.Exception;
                        throw errorFeature.Exception;
                    }
                })
                .RequireAuthorization(WPProxySettings.AuthorizationPolicy);

                endpoints.MapDefaultControllerRoute();
            });
        }
Exemplo n.º 22
0
        private void SettingsClick(object sender, EventArgs e)
        {
            IHttpProxy proxy = GetCurrentProxy();

            if (proxy != null)
            {
                ProxySetup setupForm = new ProxySetup(proxy);
                setupForm.ShowDialog();
            }
        }
Exemplo n.º 23
0
 private void UpdateStartStopButtonStatus(IHttpProxy proxy)
 {
     if (proxy.IsListening)
     {
         _buttonStart.Image = Resources.pause1;
     }
     else
     {
         _buttonStart.Image = Resources.play;
     }
 }
 public ProxyInvokerMiddleware(
     RequestDelegate next,
     ILogger <ProxyInvokerMiddleware> logger,
     IOperationLogger <ProxyInvokerMiddleware> operationLogger,
     IHttpProxy httpProxy)
 {
     _next            = next ?? throw new ArgumentNullException(nameof(next));
     _logger          = logger ?? throw new ArgumentNullException(nameof(logger));
     _operationLogger = operationLogger ?? throw new ArgumentNullException(nameof(operationLogger));
     _httpProxy       = httpProxy ?? throw new ArgumentNullException(nameof(httpProxy));
 }
Exemplo n.º 25
0
 public ProxyInvokerMiddleware(
     RequestDelegate next,
     ILogger <ProxyInvokerMiddleware> logger,
     IHttpProxy httpProxy,
     IRandomFactory randomFactory)
 {
     _next          = next ?? throw new ArgumentNullException(nameof(next));
     _logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     _httpProxy     = httpProxy ?? throw new ArgumentNullException(nameof(httpProxy));
     _randomFactory = randomFactory ?? throw new ArgumentNullException(nameof(randomFactory));
 }
Exemplo n.º 26
0
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            var code = httpProxy.QueryString["code"];

            if (code != null)
            {
                var tranid   = httpProxy.QueryString["state"];
                var filepath = Helper.GetSaveFilePath() + "\\" + tranid;
                var dict     = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText(filepath, System.Text.Encoding.UTF8));
                try
                {
                    System.IO.File.Delete(filepath);
                }
                catch { }
                string appId     = dict["appId"];
                string secret    = dict["secret"];
                string returnUrl = dict["returnUrl"];
                if (returnUrl.Contains("?"))
                {
                    returnUrl += "&";
                }
                else
                {
                    returnUrl += "?";
                }

                try
                {
                    var url      = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={System.Web.HttpUtility.UrlEncode(appId, Encoding.UTF8)}&secret={System.Web.HttpUtility.UrlEncode(secret, Encoding.UTF8)}&code={System.Web.HttpUtility.UrlEncode(code, Encoding.UTF8)}&grant_type=authorization_code";
                    var content  = Helper.GetWebContent(url, 8);
                    var tokenObj = Newtonsoft.Json.JsonConvert.DeserializeObject <weixin_token>(content);
                    if (tokenObj.errmsg != null)
                    {
                        returnUrl += $"err={System.Web.HttpUtility.UrlEncode(tokenObj.errmsg, Encoding.UTF8)}";
                    }
                    else
                    {
                        returnUrl += $"openid={System.Web.HttpUtility.UrlEncode(tokenObj.openid, Encoding.UTF8)}&access_token={System.Web.HttpUtility.UrlEncode(tokenObj.access_token, Encoding.UTF8)}";
                    }
                }
                catch (Exception ex)
                {
                    var err = ex;
                    while (err.InnerException != null)
                    {
                        err = err.InnerException;
                    }
                    returnUrl += $"err={System.Web.HttpUtility.UrlEncode(err.Message, Encoding.UTF8)}";
                }
                httpProxy.Redirect(returnUrl);
            }
            return(TaskStatus.Completed);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Return current active proxy.
        /// </summary>
        public bool TryGetProxy(out IHttpProxy proxy)
        {
            proxy = null;

            if (_httpProxyState.TryGetTarget(out var state) && state.Proxy != null)
            {
                proxy = new HttpProxy(state.Proxy);
                return(true);
            }

            return(false);
        }
Exemplo n.º 28
0
        public static string Post(string url, string jsonData, IHttpProxy proxy)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/json";
            request.Timeout = 10 * 1000;
            if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
            {
                if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port);
                }
                else
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port)
                    {
                        Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
                    };
                }
            }
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(jsonData);
                streamWriter.Flush();
                streamWriter.Close();
            }

            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                Log.Error(e);
                return string.Empty;
            }

            return string.Empty;
        }
Exemplo n.º 29
0
 public ReverseProxyMiddleware(
     RequestDelegate nextMiddleware,
     MemorySingletonProxyConfigProvider proxyConfigProvider,
     IHttpProxy httpProxy,
     ProxyHttpClientProvider clientProvider,
     AcmeChallengeSingleton acmeChallengeSingleton)
 {
     _nextMiddleware         = nextMiddleware;
     _proxyConfigProvider    = proxyConfigProvider;
     _httpProxy              = httpProxy;
     _httpClient             = clientProvider.GetClient();
     _acmeChallengeSingleton = acmeChallengeSingleton;
 }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }

                    Newtonsoft.Json.Linq.JObject orderJSONObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["tradeDetail"]);
                    string orderId         = orderJSONObj.Value <string>("orderId");
                    double settleAmount    = orderJSONObj.Value <double>("settleAmount");
                    double commisionAmount = orderJSONObj.Value <double>("commisionAmount");
                    if (ResturantFactory.ResturantListener != null)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                ResturantFactory.ResturantListener.OnReceiveOrderSettlement(ResturantPlatformType.Meituan, orderId, new ServiceAmountInfo()
                                {
                                    PlatformServiceAmount = commisionAmount,
                                    SettleAmount          = settleAmount
                                });
                            }
                            catch { }
                        }).Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团SettlementCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
                throw ex;
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");

            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            try
            {
                var requestJson = httpProxy.Form["requestJson"];
                if (!string.IsNullOrEmpty(requestJson))
                {
                    var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(requestJson);
                    var tradeId     = responseObj.body["out_trade_no"].ToString();
                    var config      = PayFactory.GetConfig <Config>(typeof(LianTuo_WeixinJsApi), tradeId);

                    string serverSign = responseObj.head["sign"].ToString();
                    if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign)
                    {
                        throw new Exception("服务器返回信息签名检验失败");
                    }

                    if ((string)responseObj.body["is_success"] == "S")
                    {
                        double?receipt_amount = null;
                        try
                        {
                            if (responseObj.body["receipt_amount"] != null)
                            {
                                receipt_amount = Convert.ToDouble(responseObj.body["receipt_amount"]);
                            }
                        }
                        catch
                        {
                        }
                        PayFactory.OnPaySuccessed(tradeId, receipt_amount, null, requestJson);
                    }
                    else if ((string)responseObj.body["is_success"] == "F")
                    {
                        PayFactory.OnPayFailed(tradeId, (string)responseObj.body["message"], requestJson);
                    }
                }
                httpProxy.ResponseWrite("success");
            }
            catch (Exception ex)
            {
                using (Log log = new Log("Jack.Pay.LianTuo.WXJSApi.Result Error", false))
                {
                    log.Log(ex.ToString());
                    log.LogJson(httpProxy.Form);
                }
            }
            return(TaskStatus.Completed);
        }
Exemplo n.º 32
0
        private static string Get(string url, string encoding, IHttpProxy proxy)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(string.Empty);
            }

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

            request.Method  = "GET";
            request.Timeout = 10 * 1000;
            if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
            {
                if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port);
                }
                else
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port)
                    {
                        Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
                    };
                }
            }

            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                        {
                            return(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(string.Empty);
            }

            return(string.Empty);
        }
Exemplo n.º 33
0
        public ProxyInvoker(
            ILogger <ProxyInvoker> logger,
            IOperationLogger operationLogger,
            ILoadBalancer loadBalancer,
            IHttpProxy httpProxy)
        {
            Contracts.CheckValue(logger, nameof(logger));
            Contracts.CheckValue(operationLogger, nameof(operationLogger));
            Contracts.CheckValue(loadBalancer, nameof(loadBalancer));
            Contracts.CheckValue(httpProxy, nameof(httpProxy));

            _logger          = logger;
            _operationLogger = operationLogger;
            _loadBalancer    = loadBalancer;
            _httpProxy       = httpProxy;
        }
Exemplo n.º 34
0
        public static WebProxy GetWebProxy(IHttpProxy proxy)
        {
            if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
            {
                if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
                {
                    return new WebProxy(proxy.Server, proxy.Port);
                }

                return new WebProxy(proxy.Server, proxy.Port)
                {
                    Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
                };
            }

            return null;
        }
Exemplo n.º 35
0
        private static string Get(string url, string encoding, IHttpProxy proxy)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.Timeout = 10 * 1000;
            if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
            {
                if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port);
                }
                else
                {
                    request.Proxy = new WebProxy(proxy.Server, proxy.Port)
                    {
                        Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
                    };
                }
            }

            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return string.Empty;
            }

            return string.Empty;
        }
Exemplo n.º 36
0
 public static HttpWebResponse CreateGetHttpResponse(string url,IHttpProxy proxy)
 {
     if (string.IsNullOrEmpty(url))
     {
         throw new ArgumentNullException("url");
     }
     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
     if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
     {
         if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
         {
             request.Proxy = new WebProxy(proxy.Server, proxy.Port);
         }
         else
         {
             request.Proxy = new WebProxy(proxy.Server, proxy.Port);
             request.Proxy.Credentials = new NetworkCredential(proxy.UserName, proxy.Password);
         }
     }
     request.Method = "GET";
     request.UserAgent = DefaultUserAgent;
     return request.GetResponse() as HttpWebResponse;
 }
Exemplo n.º 37
0
Arquivo: Http.cs Projeto: xieby/Wox
 public static IWebProxy WebProxy(IHttpProxy proxy)
 {
     if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
     {
         if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
         {
             var webProxy = new WebProxy(proxy.Server, proxy.Port);
             return webProxy;
         }
         else
         {
             var webProxy = new WebProxy(proxy.Server, proxy.Port)
             {
                 Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
             };
             return webProxy;
         }
     }
     else
     {
         return WebRequest.GetSystemWebProxy();
     }
 }
Exemplo n.º 38
0
Arquivo: Http.cs Projeto: xieby/Wox
 /// <exception cref="WebException">Can't download file </exception>
 public static void Download([NotNull] string url, [NotNull] string filePath, IHttpProxy proxy)
 {
     var client = new WebClient { Proxy = WebProxy(proxy) };
     client.DownloadFile(url, filePath);
 }
Exemplo n.º 39
0
Arquivo: Google.cs Projeto: xieby/Wox
 public Google(IHttpProxy httpProxy) : base(httpProxy)
 {
 }
Exemplo n.º 40
0
 public Baidu(IHttpProxy httpProxy) : base(httpProxy)
 {
 }
Exemplo n.º 41
0
 public static string Get(string url, IHttpProxy proxy, string encoding = "UTF-8")
 {
     return Get(url, encoding, proxy);
 }
Exemplo n.º 42
0
 public AbstractSuggestionSource(IHttpProxy httpProxy)
 {
     Proxy = httpProxy;
 }