【问题标题】:HTTP Post to another IP Inside HTTP HandlerHTTP Post 到 HTTP 处理程序内的另一个 IP
【发布时间】:2014-11-17 15:17:57
【问题描述】:

场景是这样的,我有一个基本的 HTTPHandler,从一个源接收 JSON,处理得很好。然后它需要发送到另一个目的地(与原件无关),但对于我的生活,无法让它发布。 使用wireshark它似乎永远不会发布数据,我想知道是不是因为它使用相同的HTTPContext所以我部署为一个新线程 - 仍然不起作用..我已经发布了代码(对不起,如果有点乱,我只是在尝试在整理之前让它工作)。 感谢您的期待,我以前使用过这里的许多文章,它们一直非常有用!

    public void ProcessRequest ( HttpContext context )
    {
        string retval = string.Empty;
        string jsonString = string.Empty;

        try
        {
            context.Response.ContentType = "text/plain; charset=utf-8";

            context.Request.InputStream.Position = 0;
            using ( var inputStream = new StreamReader( context.Request.InputStream ) )
                jsonString = inputStream.ReadToEnd();

            //debug only
            var jsonObject = JsonConvert.DeserializeObject<GitlabPost>( jsonString );

            retval =
                string.Format(
                    "JSON Received {0}",
                    DateTime.Now.ToUniversalTime() );
            context.Response.Write( retval );   //respond to gitlab, tell it received ok.

            //now have json object, spit it out to axosoft. 
            var hashedJSON = string.Format("{0}{1}", jsonString, AXOSOFT_API_KEY);

            SHA256 hash = SHA256Managed.Create();
            Byte[] result = hash.ComputeHash( System.Text.Encoding.ASCII.GetBytes( hashedJSON ) );

            hashedJSON = result.Aggregate( "", ( current, x ) => current + string.Format( "{0:x2}", x ) );

            Thread jsonPostThread = new Thread(() => SendAxosoftJSON(jsonString, hashedJSON) ) ;
            jsonPostThread.Start();
        }
        catch (Exception error)
        {
            string err = error.Message;

            context.Response.ContentType = "text/plain; charset=utf-8"; //"application/xml";
            retval =
                string.Format(
                    "JSON Post Failed at {0} because {1}",
                    DateTime.Now.ToUniversalTime(), err );
            context.Response.Write( retval );
        }
    }

发帖的主线是这样的:

    private void SendAxosoftJSON(string jsonString, string hashedJSON)
    {
        var req =
                (HttpWebRequest)
                WebRequest.Create( AXOSOFT_URL + hashedJSON );

        req.ContentType = "application/json";
        req.Method = "POST";

        using (var sw = new StreamWriter( req.GetRequestStream() ))
        {
            sw.Write( jsonString );
            sw.Flush();
            sw.Close();
        }
        req.GetResponse();
     }

【问题讨论】:

    标签: c# http post httphandler


    【解决方案1】:

    对于现在看到这个的任何人,我解决了这个问题,一旦我弄清楚了搜索词,谷歌就有很多结果!它称为中继,代码如下......我遇到的主要问题是代理!由于我在公司代理后面,因此响应被定向到代理,并且失败了。

        public void ProcessRequest ( HttpContext context )
        {
            string retval = string.Empty;
            string jsonString = string.Empty;
    
            try
            {
                    System.Diagnostics.Debug.WriteLine( "Received Post From GitLab." );
                context.Response.ContentType = "text/plain; charset=utf-8"; //"application/xml";
    
                HttpRequest original = context.Request;
    
                context.Request.InputStream.Position = 0;
                using (var inputStream = new StreamReader( context.Request.InputStream ))
                    jsonString = inputStream.ReadToEnd();
    
                byte[] originalstream = System.Text.Encoding.ASCII.GetBytes( jsonString );
                    System.Diagnostics.Debug.WriteLine( originalstream );
    
                #region respond to gitlab
                retval =
                            string.Format(
                                "JSON Received {0}",
                                DateTime.Now.ToUniversalTime() );
                context.Response.Write( retval );   //respond to gitlab, tell it received ok. (no 500)
                System.Diagnostics.Debug.WriteLine( "Responded to GitLab" ); 
                #endregion
    
                var jsonObject = JsonConvert.DeserializeObject<GitlabPost>( jsonString );
                    System.Diagnostics.Debug.WriteLine( "Stringified JSON" );
    
                //now have json object, spit it out to axosoft. 
                var hashedJSON = string.Format( "{0}{1}", jsonString, _axosoftAPIKey );
                    System.Diagnostics.Debug.WriteLine( hashedJSON );
                SHA256 hash = SHA256.Create();
                Byte[] result = hash.ComputeHash( System.Text.Encoding.ASCII.GetBytes( hashedJSON ) );
    
                hashedJSON = result.Aggregate( "", ( current, x ) => current + string.Format( "{0:x2}", x ) );
                    System.Diagnostics.Debug.WriteLine( "Hashed JSON from GitLab" );
    
                //now create the request to axosoft.
                HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create( new Uri( _axosoftUrl + hashedJSON ) );
                    System.Diagnostics.Debug.WriteLine( "Opened Request to Axosoft." );
    
                //copy over headers.
                newRequest.ContentType = original.ContentType;
                newRequest.Method = original.HttpMethod;
                newRequest.UserAgent = original.UserAgent;
                newRequest.Proxy = null;
    
                Stream reqStream = newRequest.GetRequestStream();
    
                reqStream.Write( originalstream, 0, originalstream.Length );
                reqStream.Close();
                    System.Diagnostics.Debug.WriteLine( "written data to stream" );
    
                try
                {
                    //send the post.
                    newRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                    {
                        var resp = (HttpWebResponse)ex.Response;
                        if (resp.StatusCode == HttpStatusCode.Created)
                        {
                            //post successful, carry on about your business.
                            System.Diagnostics.Debug.WriteLine( "201 Created" );
                        }
                        else if (resp.StatusCode == HttpStatusCode.NotFound)
                        {
                            //404
                            System.Diagnostics.Debug.WriteLine( "404 Not Found" );
                        }
                        else if (resp.StatusCode == HttpStatusCode.OK)
                        {
                            //200
                            System.Diagnostics.Debug.WriteLine( "200 OK" );
                        }
                        else
                        {
                            //unknown!
                            System.Diagnostics.Debug.WriteLine( string.Format( "Unknown Status: {0}", resp.StatusCode ) );
                        }
                    }
                    else
                    {   // dont actually throw exception in production code, that would be stupid...
                        throw new Exception("unknown exception in GetResponse(): " + ex.Message);
                    }
                }
                System.Diagnostics.Debug.WriteLine( "Sent Post Data.." );
            }
            catch (Exception error)
            {
                string err = error.Message;
                System.Diagnostics.Debug.WriteLine( "Exception: " + err );
    
                context.Response.ContentType = "text/plain; charset=utf-8"; //"application/xml";
                retval =
                    string.Format(
                        "JSON Post Failed at {0} because {1}",
                        DateTime.Now.ToUniversalTime(), err );
                context.Response.Write( retval );
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2013-03-24
      • 2019-08-27
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 2010-12-08
      相关资源
      最近更新 更多