2015年9月16日 星期三

JSON & PHP & curl 的使用

利用 JSON來做為 Server (使用 php) 與 Client (使用 curl) 之間訊息溝通的橋樑
將分為幾個部分 
1. Client 發送 JSON格式的訊息給 Server
2. Server 接收 JSON格式訊息,並做 Parse處理
3. Server 以 JSON格式訊息回覆給 Client
4. Client 接收 Server回覆訊息,並做 Parse處理

1. Client 發送 JSON格式的訊息給 Server
    這裡分為兩部分
    a. curl post 格式產生
    b. jsoon 格式產生


    a. curl post 格式產生

int SendMessageByJson(const char* url, const char* jsonData) 
{
        CURL *curl;
CURLcode res;

curl = curl_easy_init();
if (!curl)
return -1;

curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POST, true);

struct curl_slist *list = NULL;

list = curl_slist_append(list, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

// 設定回饋機制, 接收 http server訊息來判斷結果如何
string response;
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);


// 做 response解析 -  在第 4 部分會處理
json_parse(response);
return res;
}
     
        b. jsoon 格式產生
        以簡單的 string to string 方式製作,較複雜的格式則再參考 JSON提供的範例或 API函式
void getJsonData(char* jasonData)
{
        cJSON* gcm_root = cJSON_CreateObject();
cJSON_AddStringToObject(gcm_root, "test", "12345");
cJSON_AddStringToObject(gcm_root, "abc", "ABCDE");
        jasonData = cJSON_Print(gcm_root);
}


2. Server 接收 JSON格式訊息,並做 Parse處理
<?php
$data = json_decode(file_get_contents('php://input'), TRUE);
echo $data['test'];
?>


3. Server 以 JSON格式訊息回覆給 Client
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
$value = "JSON Data Test";
$arr["hello"] = $value;
echo json_encode($arr); 
?>

4. Client 接收 Server回覆訊息,並做 Parse處理
void json_parse(const string& response)
{
cJSON* obj;

obj = cJSON_Parse(response.c_str());

        // 做解析 Key的處理,再轉為 char* 格式
cJSON* firstValue = cJSON_GetObjectItem(obj, "hello");
char* str = cJSON_Print(firstValue);
}

沒有留言:

張貼留言