2011年8月3日 星期三

[C#] POST 傳值

之前有一個動作需要post到數個不同的地方做檢驗,
所以就把這整理成一個Function

用法很簡單,
uri為要post傳送出去的網址
parameters為要傳送的字串

<EX> parameters="gamecode=Vmtab2QxZHNRbEpRVkRBOSpQ&transpoint=999"


    string HttpPost(string uri, string parameters)
    {  
        WebRequest webRequest = WebRequest.Create(uri);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(parameters);
        Stream os = null;
        try
        { // send the Post
            webRequest.ContentLength = bytes.Length;   //Count bytes to send
            os = webRequest.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);         //Send it
        }
        catch (WebException ex)
        {
            Response.Write(" <script   language=JavaScript> alert( 'HttpPost: Request error'); </script> "); 
        }
        finally
        {
            if (os != null)
            {
                os.Close();
            }
        }
        try
        { // get the response
            WebResponse webResponse = webRequest.GetResponse();
            if (webResponse == null)
            { return null; }
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            return sr.ReadToEnd().Trim();
        }
        catch (WebException ex)
        {
            Response.Write(" <script   language=JavaScript> alert( 'HttpPost: Response error'); </script> ");
        }
        return null;
    } // end HttpPost 

沒有留言:

張貼留言