วันศุกร์ที่ 27 สิงหาคม พ.ศ. 2553

ฟังก์ชั่น C# สำหรับ WebRequest ผ่าน http (แก้ปัญหาการ Post ภาษาไทย)

string HttpPost(string uri, string parameters)

{



// parameters: name1=value1&name2=value2

WebRequest webRequest = WebRequest.Create(uri);

//string ProxyString =

// System.Configuration.ConfigurationManager.AppSettings

// [GetConfigKey("proxy")];

//webRequest.Proxy = new WebProxy (ProxyString, true);

//Commenting out above required change to App.Config

webRequest.ContentType = "application/x-www-form-urlencoded";

webRequest.Method = "POST";

//แก้ปัญหาการส่งภาษไทยแล้วกลายเป็นภาษายึกยือ





Encoding thaiEnc = Encoding.GetEncoding("iso-8859-11");

byte[] bytes = thaiEnc.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)

{



MessageBox.Show(ex.Message, "HttpPost: Request error",

MessageBoxButtons.OK, MessageBoxIcon.Error);

}



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)

{



MessageBox.Show(ex.Message, "HttpPost: Response error",

MessageBoxButtons.OK, MessageBoxIcon.Error);

}



return null;

}

}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น