[C#] HttpWebRequest 클래스를 이용한 POST 전송하기.



http://onlybalance.pe.kr/xe/?category=99&mid=tech&document_srl=378&sort_index=readed_count&order_type=desc


[C#] HttpWebRequest 클래스를 이용한 POST 전송하기
01.protected void SendSMS()
02.{
03.String[] messages = new String[6];
04.messages[0] = "행정과";         // 아이디
05.messages[1] = "암호";           // 암호
06.messages[2] = "11111111111";    // 보내는 사람 번호
07.messages[3] = "22222222222";    // 받는 사람 번호
08.messages[4] = "테스트 메시지";  // 메시지
09.messages[5] = "홍길동";         // 받는 사람 이름
10.String postData = String.Format("id={0}&pw={1}&sender={2}&receiver={3}&msg={4}&idreserve={5}", messages[0], messages[1], messages[2], messages[3], messages[4], messages[5]);
11. 
12.HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("http://localhost:38080/encoding/encoding.jsp");
13.// 인코딩 1 - UTF-8
14.byte[] sendData = UTF8Encoding.UTF8.GetBytes(postData);
15.httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
16.// 인코딩 2 - EUC-KR
17.//byte[] sendData = Encoding.GetEncoding("EUC-KR").GetBytes(postData);
18.//httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=EUC-KR";
19.httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
20.httpWebRequest.Method = "POST";
21.// Set the content length of the string being posted.
22.httpWebRequest.ContentLength = sendData.Length;
23.Stream requestStream = httpWebRequest.GetRequestStream();
24.requestStream.Write(sendData, 0, sendData.Length);
25.requestStream.Close();
26.HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
27.StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("EUC-KR"));    // Encoding.GetEncoding("EUC-KR")
28.string html = streamReader.ReadToEnd();
29.streamReader.Close();
30.httpWebResponse.Close();
31. 
32.text.Value = html;
33.}

This is an easy way to make a JSON POST request to a remote service using C#:

1
2
3
4
5
6
7
8
9
10
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();

Notice that in line 4 we create an instance of DataContractJsonSerializer (Assembly: System.ServiceModel.Web) and initialize it with the type of object we are serializing as JSON to send to the service. In lines 5 and 6 the serializer writes the object into a Stream. Line 7 transforms the Stream into an UTF-8 String (as the content-type) and finally in lines 8 to 10 we send the data to the service.


약간의 문제가 발생하게 되는데

x-www-form-urlencoded 방식의 경우에 get 방식의 id=value&id2=value2 같은 방식으로 처리된다. (텍스트로)

그래서 JSON 으로 변환된 문자열을 전송할 경우에 & 문자가 있으면 의도하지 않은 에러가 발생한다.


그래서 serialize 된 문자열에서 


string postData = string.Format("shot={0}", JsonConvert.SerializeObject(shot));

                postData = postData.Replace("&", "%26");

                //string postData = string.Format("shot=TTT", JsonConvert.SerializeObject(shot));

                query_string = "exec=updateshot";

                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://shots.php?" + query_string);

                httpWebRequest.ContentType = "text/json";

                byte[] sendData = UTF8Encoding.UTF8.GetBytes(postData);

                httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";              

                httpWebRequest.Method = "POST";

                httpWebRequest.ContentLength = sendData.Length;


                Stream requestStream = httpWebRequest.GetRequestStream();

                requestStream.Write(sendData, 0, sendData.Length);

                requestStream.Close();


                HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();


                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8"));    // Encoding.GetEncoding("EUC-KR")

                string shot_id = streamReader.ReadToEnd();

                streamReader.Close();

                httpWebResponse.Close();


postData = postData.Replace("&", "%26");

처럼 처리해주면 에러를 피할 수 있다.