Thursday, September 29, 2011

[C#] WebRequest Post with Header

最近有個需求,需要用HTTP Post一段資訊,而且不是用Query String的方式,然後還要在Header中加認證資訊,之前用的WebRequest方式都不適用,於是找了新的方式,主要是參考How to: Send Data Using the WebRequest Class,我有做了一些修改,主要是Encoding跟Header的部分,剩下的差不多。

語法大概是長這樣,不過我是拿專案內的function貼過來才改的,直接拿去用如果不會動,可能是有哪邊改壞了XD,反正意思到了就好。

string GetRequest()
{
            string body = "Line 1" + Environment.NewLine +
            "Line 2" + Environment.NewLine 
            "Line 3" + Environment.NewLine ;
            string Link = "http://www.died.tw";
            string header = "PASSWORD";

            byte[] byteArray = Encoding.GetEncoding("Big5").GetBytes(body);
            WebRequest request = WebRequest.Create(Link);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Authorization", header);  //Header名稱自己改
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            string ResultCode = ((HttpWebResponse)response).StatusCode.ToString();
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("Big5"));
            string Result = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();

                if (ResultCode == "OK")
                {
                    return Result;
                }
                else
                {
                    return null;
                }
}


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...