本文目錄一覽:
- 1、如何使用curl將數組放入json對象
- 2、PHP如何通過Post請求發送Json數據
- 3、php用curl的post方法傳遞json包的時候,接受方是怎麼獲取的呢
- 4、為什麼要使用curl傳輸json
- 5、如何用curl post 一段包含中文json的文本到服務器
如何使用curl將數組放入json對象
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, ORDERPOSTURL); //抓取指定網頁
curl_setopt($ch, CURLOPT_HEADER, 0); //設置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //設置是否返回信息
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);//發送數據
$response = curl_exec($ch); //接收返回信息
if (curl_errno($ch)) {
//出錯則記錄錯誤信息
Logger::getLogger(“reqLogger”)-error(“錯誤信息:” . curl_error($ch));
}
curl_close($ch); //關閉curl鏈接
$obj=json_decode($myLogger);//json字符串轉化為對象
$arry=json_decode($response,true);//json字符串轉化為數組
PHP如何通過Post請求發送Json數據
首先要把數據轉換成json格式,再通過curl方法調用接口並傳參數
代碼如下:
$keyword = urlencode($_POST[‘keyword’]);
$parameters = json_encode(array(‘keyWord’=$keyword,’areaCode’=’*’));
$post_data[‘appToken’] = “323ds7674354fds32fdsda60173”;//隨便寫的
$post_data[‘parameters’] = $parameters;
$url = ”;//隨便寫的
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//用post方法傳送參數
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
之後就返回數據即可。
php用curl的post方法傳遞json包的時候,接受方是怎麼獲取的呢
假設POST的數據為:{“data”:”abc”}
POST參數為:data
同樣以PHP為例,接受並處理請求的相關代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
?php
extract($_POST); // 將數組中的key攤成變量,並導入key對應的值
if (!empty($data))
{
$data = json_decode($data); // json 字符串解碼成 json 數據
var_dump($data); // 打印 json 數據
// 輸出結果
object(stdClass)[1]
public ‘data’ = string ‘abc’ (length=3)
}
為什麼要使用curl傳輸json
//使用curl庫,以post方式向服務器發送json數據
//json數據的組合可以參考jsoncpp庫,也可以按json格式自己組合字符串
//注意事項,以下代碼不可以多線程執行,如果多線程執行,需要加鎖進行控制,否則會運行崩潰
[cpp] view plain copy
#include curl/curl.h
#include string
#include exception
int main(int argc, char *argv[])
{
char szJsonData[1024];
memset(szJsonData, 0, sizeof(szJsonData));
std::string strJson = “{“;
strJson += “\”user_name\” : \”test\”,”;
strJson += “\”password\” : \”test123\””;
strJson += “}”;
strcpy(szJsonData, strJson.c_str());
try
{
CURL *pCurl = NULL;
CURLcode res;
// In windows, this will init the winsock stuff
curl_global_init(CURL_GLOBAL_ALL);
// get a curl handle
pCurl = curl_easy_init();
if (NULL != pCurl)
{
// 設置超時時間為1秒
curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);
// First set the URL that is about to receive our POST.
// This URL can just as well be a
// https:// URL if that is what should receive the data.
curl_easy_setopt(pCurl, CURLOPT_URL, “”);
//curl_easy_setopt(pCurl, CURLOPT_URL, “”);
// 設置http發送的內容類型為JSON
curl_slist *plist = curl_slist_append(NULL,
“Content-Type:application/json;charset=UTF-8”);
curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);
// 設置要POST的JSON數據
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);
// Perform the request, res will get the return code
res = curl_easy_perform(pCurl);
// Check for errors
if (res != CURLE_OK)
{
printf(“curl_easy_perform() failed:%s\n”, curl_easy_strerror(res));
}
// always cleanup
curl_easy_cleanup(pCurl);
}
curl_global_cleanup();
}
catch (std::exception ex)
{
printf(“curl exception %s.\n”, ex.what());
}
return 0;
}
如何用curl post 一段包含中文json的文本到服務器
1. JSON的數據格式
a) 按照最簡單的形式,可以用下面這樣的 JSON 表示名稱/值對:
{ “firstName”: “Brett” }
b) 可以創建包含多個名稱/值對的記錄,比如:
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” }
c) 可以創建值的數組
{ “people”: [
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “lastName”:”Hunter”, “email”: “jason@servlets.com” }
]}
d) 當然,可以使用相同的語法表示多個值(每個值包含多個記錄):
{ “programmers”: [
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “lastName”:”Hunter”, “email”: “jason@servlets.com” }
],
“authors”: [
{ “firstName”: “Isaac”, “lastName”: “Asimov”, “genre”: “science fiction” },
{ “firstName”: “Tad”, “lastName”: “Williams”, “genre”: “fantasy” }
],
“musicians”: [
{ “firstName”: “Eric”, “lastName”: “Clapton”, “instrument”: “guitar” }
]
}
注意,在不同的主條目(programmers、authors 和 musicians)之間,記錄中實際的名稱/值對可以不一樣。JSON 是完全動態的,允許在 JSON 結構的中間改變表示數據的方式。
2. 在 JavaScript 中使用 JSON
JSON 是 JavaScript 原生格式,這意味着在 JavaScript 中處理 JSON 數據不需要任何特殊的 API 或工具包。
2.1 將 JSON 數據賦值給變量
例如,可以創建一個新的 JavaScript 變量,然後將 JSON 格式的數據字符串直接賦值給它:
var people =
{ “programmers”: [
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “lastName”:”Hunter”, “email”: “jason@servlets.com” }
],
“authors”: [
{ “firstName”: “Isaac”, “lastName”: “Asimov”, “genre”: “science fiction” },
{ “firstName”: “Tad”, “lastName”: “Williams”, “genre”: “fantasy” }
],
“musicians”: [
{ “firstName”: “Eric”, “lastName”: “Clapton”, “instrument”: “guitar” }
]
}
2.2 訪問數據
將這個數組放進 JavaScript 變量之後,就可以很輕鬆地訪問它。實際上,只需用點號表示法來表示數組元素。所以,要想訪問 programmers 列表的第一個條目的姓氏,只需在JavaScript 中使用下面這樣的代碼:
people.programmers[0].lastName;
注意,數組索引是從零開始的。
2.3 修改 JSON 數據
正如訪問數據,可以按照同樣的方式修改數據:
people.musicians[1].lastName = “Rachmaninov”;
2.4 轉換回字符串
a) 在 JavaScript 中這種轉換也很簡單:
String newJSONtext = people.toJSONString();
b) 可以將任何 JavaScript 對象轉換為 JSON 文本。並非只能處理原來用 JSON 字符串賦值的變量。為了對名為 myObject 的對象進行轉換,只需執行相同形式的命令:
String myObjectInJSON = myObject.toJSONString();
說明:將轉換回的字符串作為Ajax調用的字符串,完成異步傳輸。
小結:如果要處理大量 JavaScript 對象,那麼 JSON 幾乎肯定是一個好選擇,這樣就可以輕鬆地將數據轉換為可以在請求中發送給服務器端程序的格式。
3. 服務器端的 JSON
3.1 將 JSON 發給服務器
a) 通過 GET 以名稱/值對發送 JSON
在 JSON 數據中會有空格和各種字符,Web 瀏覽器往往要嘗試對其繼續編譯。要確保這些字符不會在服務器上(或者在將數據發送給服務器的過程中)引起混亂,需要在JavaScript的escape()函數中做如下添加:
var url = “organizePeople.php?people=” + escape(people.toJSONString());
request.open(“GET”, url, true);
request.onreadystatechange = updatePage;
request.send(null);
b) 利用 POST 請求發送 JSON 數據
當決定使用 POST 請求將 JSON 數據發送給服務器時,並不需要對代碼進行大量更改,如下所示:
var url = “organizePeople.php?timeStamp=” + new Date().getTime();
request.open(“POST”, url, true);
request.onreadystatechange = updatePage;
request.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
request.send(people.toJSONString());
注意:賦值時格式必須是var msg=eval(‘(‘ + req.responseText + ‘)’);
3.2 在服務器上解釋 JSON
a) 處理 JSON 的兩步驟。
針對編寫服務器端程序所用的語言,找到相應的 JSON 解析器/工具箱/幫助器 API。
使用 JSON 解析器/工具箱/幫助器 API 取得來自客戶機的請求數據並將數據轉變成腳本能理解的東西。
b) 尋找 JSON 解析器
尋找 JSON 解析器或工具箱最好的資源是 JSON 站點。如果使用的是 Java servlet,json.org 上的 org.json 包就是個不錯的選擇。在這種情況下,可以從 JSON Web 站點下載 json.zip 並將其中包含的源文件添加到項目構建目錄。編譯完這些文件後,一切就就緒了。對於所支持的其他語言,同樣可以使用相同的步驟;使用何種語言取決於您對該語言的精通程度,最好使用您所熟悉的語言。
c) 使用 JSON 解析器
一旦獲得了程序可用的資源,剩下的事就是找到合適的方法進行調用。如果在 servlet 中使用的是 org.json 包,則會使用如下代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { //report an error }
try {
JSONObject jsonObject = new JSONObject(jb.toString());
} catch (ParseException e) {
// crash and burn
throw new IOException(“Error parsing JSON request string”);
}
// Work with the data using methods like…
// int someInt = jsonObject.getInt(“intParamName”);
// String someString = jsonObject.getString(“stringParamName”);
// JSONObject nestedObj = jsonObject.getJSONObject(“nestedObjName”);
// JSONArray arr = jsonObject.getJSONArray(“arrayParamName”);
// etc…
}
原創文章,作者:SIOC,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/141805.html