A. 如何用curl post 一段包含中文json的文本到伺服器
1. JSON的數據格式
a) 按照最簡單的形式,可以用下面這樣的 JSON 表示名稱/值對:
{ "firstName": "Brett" }
b) 可以創建包含多個名稱/值對的記錄,比如:
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }
c) 可以創建值的數組
{ "people": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }
]}
d) 當然,可以使用相同的語法表示多個值(每個值包含多個記錄):
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }
],
"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": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }
],
"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...
}
B. 如何post一個json格式的數據
在Android/java平台上實現POST一個json數據:
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
用curl可執行如下命令:
curl -l -H "Content-type: application/json" -X POST -d '{"phone":"13521389587","password":"test"}'
用jQuery:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
PHP用cUrl實現:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init(');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
。。。
C. 如何用curl post 一段包含中文json的文本到伺服器
一般中文json_encode之後會變成uxxxx的格式了,只要使用正規的json_encode處理,
不需要考慮中文問題。
至於如何post數據到伺服器,需要設定header,參考代碼如下:
<?php
#json數據
$url='http://test.com/curl/testPostJsonData.php';
$data='{"a":"b"}';
$length=strlen($data);
$header=array(
'Content-Length:'.$length,//不是必需的
'Content-Type:text/json',
);
$ch=curl_init($url);//初始化curl
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$content=curl_exec($ch);//執行並存儲結果
curl_close($ch);
echo$content;
服務端需要使用$data=file_get_contents('php://input');獲取數據。
更多PHPcURL內容請參考我的博客《PHPcURL實現模擬登錄與採集使用方法詳解教程》
D. php curl post json數據字元串什麼寫
在我的博客《PHP cURL實現模擬登錄與採集使用方法詳解》中「十一、發送與獲取json數據」對這個問題做了詳細講解,下面是示例代碼:
<?php
#json數據
$url='http://test.com/curl/testPostJsonData.php';
$data='{"a":"b"}';//數據格式1:直接json格式類型數據
$length=strlen($data);
$header=array(
'Content-Length:'.$length,//不是必需的
'Content-Type:text/json',
);
$ch=curl_init($url);//初始化curl
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$content=curl_exec($ch);//執行並存儲結果
curl_close($ch);
echo$content;
#數據格式2: 分割數據
$data=[
'name:Zjmainstay',
'website:http://www.zjmainstay.cn',
];
$data=implode(" ",$data);
#數據格式3:&分割數據
$data='name:Zjmainstay&website:http://www.zjmainstay.cn';
文章還涉及很多php curl相關內容,如需了解,請訪問查看。
E. windows下使用curl利用post發送json數據時注意事項
在window中linux格式下的單引號要改成雙引號,json格式數據中雙引號要加\轉義