HTTP发布到另一个IP内部HTTP处理程序

时间:2014-11-17 15:17:58

标签: c# http post httphandler

场景是这样的,我有一个基本的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();
     }

1 个答案:

答案 0 :(得分:0)

对于现在正在看这个的人,我解决了这个问题,谷歌有一些结果我曾经想过搜索条件了!它叫做中继,代码在下面......我遇到的主要问题是代理!因为我支持公司代理,所以响应被定向到代理,并且失败了。

    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 );
        }
    }
}