'JSON'에 해당되는 글 2건

  1. 2012.04.26 PHP에서 json post 를 처리하는 방법.
  2. 2012.04.26 [C#] HttpWebRequest 클래스를 이용한 POST 전송하기.

PHP에서 json post 를 처리하는 방법.

How to Handle JSon POST Request Using PHP


http://edwin.baculsoft.com/2011/12/how-to-handle-json-post-request-using-php/


On my last project, i need to create a php service using JSon to handle service requests from multiple clients. My PHP file would consume JSon string for its requests and produce JSon string as its responses.
Im not too familiar with PHP, but after sometime googling i’ve found a workaround. This is how i do it.

01<?php
02// JSon request format is :
03// {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}
04 
05// read JSon input
06$data_back = json_decode(file_get_contents('php://input'));
07 
08// set json string to php variables
09$userName = $data_back->{"userName"};
10$password = $data_back->{"password"};
11$emailProvider = $data_back->{"emailProvider"};
12 
13// create json response
14$responses = array();
15for ($i = 0; $i < 10; $i++) {
16    $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
17}
18 
19// JSon response format is :
20// [{"name":"eeee","email":"eee@zzzzz.com"},
21// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]
22 
23// set header as json
24header("Content-type: application/json");
25 
26// send response
27echo json_encode($responses);
28?>

This is the http header and body of request and response.

Hope it help others, have fun with JSon


지난글에서 C# 으로 post json 데이터를 날리는 경우에는

Content-Type 가 

application/x-www-form-urlencoded 

인 경우에는 $_POST[postData] 로 받아서 처리하면 되는데.


Content-Type 자체가 

application/json

인 경우에는 php 에서 위와 같이 처리한다.

[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");

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



prev 1 next