首页 > 编程知识 正文

curl传递json(curl传递变量)

时间:2023-12-08 14:00:32 阅读:313414 作者:OJDG

本文目录一览:

  • 1、如何使用curl将数组放入json对象
  • 2、如何用curl post 一段包含中文json的文本到服务器
  • 3、为什么要使用curl传输json
  • 4、php用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字符串转化为数组

如何用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...

}

为什么要使用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:%sn", 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;

}

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)

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。