cjson libcurl 发送请求给python 接受数据和处理数据 参考了一下别人的方法

5 篇文章 0 订阅
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <curl/curl.h>  
#include <cJSON/cJSON.h>
//#define POSTURL    "http://www.xiami.com/member/login"  
#define POSTURL    "http://192.168.169.1:10099/reg"  
#define POSTFIELDS "username=dsb12&password=1"  
#define FILENAME   "curlposttest.log"  

//解决办法 动态数组 控制buf的大小
typedef struct UserData
{
    char* buf;
    int len;// alloc  这里没作处理 应该随时根据长度 rellaoc重新分配才对
    int used; // used length realloc:
}UserData; 

struct curl_slist* headers = NULL;


UserData d;

void parse(char* jsonbuf)
{
    cJSON* root = cJSON_Parse(jsonbuf);

    cJSON* result = cJSON_GetObjectItem(root, "result");
    printf("%s=%s\n", result->string, result->valuestring);


     cJSON* shuju  = cJSON_GetObjectItem(root, "datas");
     cJSON* code = cJSON_GetObjectItem(shuju, "code");

     printf("%s=%g\n", code->string, code->valuedouble);

     cJSON* myarr = cJSON_GetObjectItem(shuju,"data");
     
     if(myarr)
     {
         int size = cJSON_GetArraySize(myarr);
	 printf("%d\n",size);
         
         int ii;

	 for(ii=0;ii<size;ii++)
	 {

		cJSON* childNode = cJSON_GetArrayItem(myarr, ii);
                
		if(childNode)
		{
			 cJSON* child = cJSON_GetObjectItem(childNode,"name");
		
			 if(child)
			 {
                         
				 //printf("Get child name : %s\n", child->valuestring);
			
    				 printf("%s=%g\n", child->string, child->valuedouble);
			 }

			 cJSON* child1 = cJSON_GetObjectItem(childNode,"info");
		
			 if(child1)
			 {
                         
				 //printf("Get child name : %s\n", child->valuestring);
			
    				 printf("%s=%s\n", child1->string, child1->valuestring);
			 }
		}
         
	 }
	 



     }

}




size_t write_data(void* buffer,size_t size,size_t nmemb,void *stream)  
{  
    memcpy(d.buf+d.len, buffer, size*nmemb);
    //strcpy(d.buf+d.len, buffer, size*nmemb);
    d.len += size*nmemb;
	FILE *fptr = (FILE*)stream;  
	fwrite(buffer,size,nmemb,fptr);  
	return size*nmemb;  
}  

int main(int argc,char *argv[])  
{  
    CURL *curl;  
    CURLcode res;  
    FILE* fptr;  
    struct curl_slist *http_header = NULL;  

    if ((fptr = fopen(FILENAME,"w")) == NULL)  
    {  
	fprintf(stderr,"fopen file error:%s\n",FILENAME);  
	return -1;  
    }  

    char username[1024];
    fgets(username, sizeof(username), stdin);
    username[strlen(username)-1]=0;
    char password[1024];
    fgets(password, sizeof(password), stdin);
    password[strlen(password)-1] = 0;

    /*
        {
            username: username,
            password: password
        }

        {}
    */

    	cJSON* json = cJSON_CreateObject();
    	cJSON_AddItemToObject(json, "username", cJSON_CreateString(username));
    	cJSON_AddItemToObject(json, "password", cJSON_CreateString(password));

    	char* json_buf = cJSON_Print(json);
    	printf("%s\n", json_buf);


    	d.buf=(char*)malloc(8192);

	curl = curl_easy_init();  
	if (!curl)  
	{  
		fprintf(stderr,"curl init failed\n");  
		return -1;  
	}  

	curl_easy_setopt(curl,CURLOPT_URL,POSTURL); //url地址  
//	curl_easy_setopt(curl,CURLOPT_POSTFIELDS,POSTFIELDS); //post参数  
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,json_buf); //post参数 不需要统>计长度 因为json 是字符串 
	curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_data); //对返回的数据进行操作的函数地址  
	curl_easy_setopt(curl,CURLOPT_WRITEDATA,fptr); //这是write_data的第四个参数值  
	curl_easy_setopt(curl,CURLOPT_POST,1); //设置问非0表示本次操作为post  
	curl_easy_setopt(curl,CURLOPT_VERBOSE,1); //打印调试信息  
	headers=curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
   	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
//	curl_easy_setopt(curl,CURLOPT_HEADER,1); //将响应头信息和相应体一起传给write_data  
//	curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应头信息location  
	//curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"/Users/zhu/CProjects/curlposttest.cookie");  

	res = curl_easy_perform(curl);  
	printf("============");
	printf("%d\n",res);
	printf("============");

	if (res != CURLE_OK)  
	{  
		switch(res)  
		{  
			case CURLE_UNSUPPORTED_PROTOCOL:  
				fprintf(stderr,"不支持的协议,由URL的头部指定\n");  
			case CURLE_COULDNT_CONNECT:  
				fprintf(stderr,"不能连接到remote主机或者代理\n");  
			case CURLE_HTTP_RETURNED_ERROR:  
				fprintf(stderr,"http返回错误\n");  
			case CURLE_READ_ERROR:  
				fprintf(stderr,"读本地文件错误\n");  
			default:  
				fprintf(stderr,"返回值:%d\n",res);  
		}  
		return -1;  
	}  
	curl_slist_free_all(headers); /* free the list again */
	curl_easy_cleanup(curl); 
	printf("%s\n",d.buf);
printf("json返回的数据长度%lu\n",strlen(d.buf));
printf("===============");
	parse(d.buf);
printf("===============");
printf("接收到的长度%d\n",d.len);

}  

上面是c的代码 

编译 

gcc 未完善的最终版.c -lcurl -lcjson

运行 ./a.out

abcd@abcd-virtual-machine:~/curl$ ./a.out 
hello
haha
{
"username": "hello",
"password": "haha"
}
* Hostname was NOT found in DNS cache
*   Trying 192.168.169.1...
* Connected to 192.168.169.1 (192.168.169.1) port 10099 (#0)
> POST /reg HTTP/1.1
Host: 192.168.169.1:10099
Accept: */*
Content-Type:application/json;charset=UTF-8
Content-Length: 45


* upload completely sent off: 45 out of 45 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: text/html; charset=utf-8
< Content-Length: 1013
< Server: Werkzeug/0.13 Python/3.6.2
< Date: Fri, 05 Jan 2018 11:46:34 GMT


* Closing connection 0
============0
============{"result": "no", "shuju": [{"name": 1, "info": "dsb12", "price": "c4ca4238a0b923820dcc509a6f75849b", "sdate": "None", "edate": "None", "id": null}, {"name": 2, "info": "d", "price": "8fa14cdd754f91cc6554c9e71929cce7", "sdate": "None", "edate": "None", "id": null}, {"name": 3, "info": "fk", "price": "b25ffa68ad761f8578cc61700c0140ed", "sdate": "None", "edate": "None", "id": null}, {"name": 4, "info": "hurry", "price": "46c48bec0d282018b9d167eef7711b2c", "sdate": "None", "edate": "None", "id": null}], "datas": {"code": 1, "data": [{"name": 1, "info": "dsb12", "price": "c4ca4238a0b923820dcc509a6f75849b", "sdate": "None", "edate": "None", "id": null}, {"name": 2, "info": "d", "price": "8fa14cdd754f91cc6554c9e71929cce7", "sdate": "None", "edate": "None", "id": null}, {"name": 3, "info": "fk", "price": "b25ffa68ad761f8578cc61700c0140ed", "sdate": "None", "edate": "None", "id": null}, {"name": 4, "info": "hurry", "price": "46c48bec0d282018b9d167eef7711b2c", "sdate": "None", "edate": "None", "id": null}]}}
json返回的数据长度1013
===============result=no
code=1
4
name=1
info=dsb12
name=2
info=d
name=3
info=fk
name=4
info=hurry
===============接收到的长度1013

测试长度是否正确 len.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{


	char *buf="{\"result\": \"no\", \"shuju\": [{\"name\": 1, \"info\": \"dsb12\", \"price\": \"c4ca4238a0b923820dcc509a6f75849b\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}, {\"name\": 2, \"info\": \"d\", \"price\": \"8fa14cdd754f91cc6554c9e71929cce7\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}, {\"name\": 3, \"info\": \"fk\", \"price\": \"b25ffa68ad761f8578cc61700c0140ed\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}, {\"name\": 4, \"info\": \"hurry\", \"price\": \"46c48bec0d282018b9d167eef7711b2c\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}], \"datas\": {\"code\": 1, \"data\": [{\"name\": 1, \"info\": \"dsb12\", \"price\": \"c4ca4238a0b923820dcc509a6f75849b\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}, {\"name\": 2, \"info\": \"d\", \"price\": \"8fa14cdd754f91cc6554c9e71929cce7\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}, {\"name\": 3, \"info\": \"fk\", \"price\": \"b25ffa68ad761f8578cc61700c0140ed\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}, {\"name\": 4, \"info\": \"hurry\", \"price\": \"46c48bec0d282018b9d167eef7711b2c\", \"sdate\": \"None\", \"edate\": \"None\", \"id\": null}]}}";


printf("%lu\n",strlen(buf));


	return 0;
}
gcc len.c

./a.out 

1031

=========================================================

下面是python代码 flask


from flask import Flask
from flask import request
import json
import mysql

import uuid
import hashlib

app = Flask("live-server")


def toJson(**kwargs):
    return json.dumps(kwargs) # 把json转换成字符串

# 创建session
def getSession():
    uuidObj = uuid.uuid1()
    uuidStr = str(uuidObj)

    # 对UUID进行 md5 hash
    print(type(uuidStr))

    # str, bytes  QString QByteArray

    return hashlib.md5(uuidStr.encode()).hexdigest()


@app.route("/addcourse", methods=['POST', 'GET'])
def addcourse():
    try:
        json = request.json
        print(json)

        session = json['session']
        name = json['name']
        desc = json['desc']
        teacher = json['teacher']
        sdate = json['sdate']
        edate = json['edate']
        price = json['price']

        conn = mysql.get_conn()
        cursor = conn.cursor()

        mysql.select(cursor, "select id from tuser where session='%s'" % session)
        if cursor.rowcount == 0:
            return toJson(result="err", reason="session error")

        sql = "insert into tcourse (name, info, price, sdate, edate) values ('%s', '%s', %d, '%s', '%s')" % (
            name, desc, price, sdate, edate
        )
        print(sql)
        mysql.insert(cursor, sql)

        mysql.select(cursor, "select max(id) from tcourse")
        courseid = cursor.fetchone()[0]

        mysql.select(cursor, "select id from tuser where name='%s'" % teacher)
        userid = cursor.fetchone()[0]

        mysql.insert(cursor, "insert into trelation (userid, courseid, relation) values(%d, %d, 0)" % (userid, courseid))
        conn.commit()

    except Exception as e:
        print(str(e))
        return toJson(result = "err", reason=str(e))
    return toJson(result='ok')

@app.route("/charge", methods=['POST', 'GET'])
def charge():
    try:
        json = request.json
        print(json)
        session = json['session']
        money = json['money']

        conn = mysql.get_conn()
        cursor = conn.cursor()

        # 1. 用户表
        #    1. 先获得原来的余额
        #    2. 相加再更新
        # 2. 充值记录表
        #    1. 插入一条记录
        mysql.select(cursor, "select balance, id from tuser where session='%s'" % session)
        if cursor.rowcount == 0:
            return toJson(result="err", reason="session error")

        record = cursor.fetchone()
        balance = record[0]
        userid = record[1]

        new_balance = balance + money
        mysql.update(cursor, "update tuser set balance=%d where id=%d" % (new_balance, userid))
        mysql.insert(cursor, "insert into tcharge (userid, money, balance) values (%d, %d, %d)" % (userid,money, new_balance))

        conn.commit()

        return toJson(result="ok", balance=new_balance)
    except Exception as e:
        return toJson(result="err", reason=str(e))




@app.route("/login", methods=['POST', 'GET'])
def login():
    try:
        json = request.json
        print(json)
        username = json['username']
        password = json['password']
        password = hashlib.md5(password.encode()).hexdigest()
        type = json['type']

        conn = mysql.get_conn()
        cursor = conn.cursor()

        mysql.select(cursor, "select * from tuser where name='%s' and pass='%s'" % (username, password))

        if cursor.rowcount == 1:
            session = getSession()
            mysql.update(cursor, "update tuser set session='%s' where name='%s'" % (session, username))
            conn.commit()

            return toJson(result = "ok", session = session)

    except Exception as e:
        return toJson(result = "err", reason = str(e))

    # 3. 返回数据给客户端
    # return
    return toJson(result = "err", reason = "username or password error")

@app.route("/reg", methods=['POST', 'GET'])
def reg():
    print(1)
    #print(request.form['username'])
    #print(request.args.post('password'))
    try:
        # 1. 获取客户端的数据
        json1 = request.json

        print(json1)
        # a = request.get_data()
        # dict1 = json.loads(a)
        # print(dict1)
        if json1 :
            username = json1['username']
            password = json1['password']
        else:
            username = request.form['username']
            password = request.form['password']
        password = hashlib.md5(password.encode()).hexdigest()

        # 2. 写入数据库
        # 使用pymysql访问数据
        conn = mysql.get_conn()
        cursor = conn.cursor()
        mysql.insert(cursor, "insert into tuser (name, pass)values('%s', '%s')" % (username, password))
        conn.commit()

    # {
    #    result: ok
    # }
    # {
    #    result: err,
    #    reason: whasdfsadf
    # }

    except Exception as e:
        return toJson(result = "err", reason = str(e))

    # 3. 返回数据给客户端
    # return

    cursor.execute("select * from tuser limit 4")
    print(cursor.rowcount)
    courses = []
    data = {}
    for i in range(cursor.rowcount):
        record = cursor.fetchone()
        course = {}
        course["name"] = record[0]
        course["info"] = record[1]
        course["price"] = record[2]
        course["sdate"] = str(record[3])
        course["edate"] = str(record[4])
        course["id"] = record[5]
        courses.append(course)
    data['code'] = 1
    data['data'] = courses
    print(data)
    print(toJson(result='no',shuju=courses,datas=data))
    return(toJson(result='no',shuju=courses,datas=data))


app.run(host="0.0.0.0", port=10099)


#{'code': 1, 'data': [{'name': 1, 'info': 'cc', 'price': 'cc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 3, 'info': 'ccc', 'price': 'ccc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 4, 'info': 'a', 'price': '0cc175b9c0f1b6a831c399e269772661', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 12, 'info': 'e', 'price': 'e1671797c52e15f763380b45e841ec32', 'sdate': 'None', 'edate': 'None', 'id': None}]}
# {"result": "no", "shuju": [{"name": 1, "info": "cc", "price": "cc", "sdate": "0", "edate": "None", "id": null}, {"name": 3, "info": "ccc", "price": "ccc", "sdate": "0", "edate": "None", "id": null}, {"name": 4, "info": "a", "price": "0cc175b9c0f1b6a831c399e269772661", "sdate": "None", "edate": "None", "id": null}, {"name": 12, "info": "e", "price": "e1671797c52e15f763380b45e841ec32", "sdate": "None", "edate": "None", "id": null}], "datas": {"code": 1, "data": [{"name": 1, "info": "cc", "price": "cc", "sdate": "0", "edate": "None", "id": null}, {"name": 3, "info": "ccc", "price": "ccc", "sdate": "0", "edate": "None", "id": null}, {"name": 4, "info": "a", "price": "0cc175b9c0f1b6a831c399e269772661", "sdate": "None", "edate": "None", "id": null}, {"name": 12, "info": "e", "price": "e1671797c52e15f763380b45e841ec32", "sdate": "None", "edate": "None", "id": null}]}}


下面是python flask 输出和返回 

192.168.169.132 - - [05/Jan/2018 19:34:09] "POST /reg HTTP/1.1" 200 -
1
{'username': 'hello', 'password': 'haha'}
4
{'code': 1, 'data': [{'name': 1, 'info': 'dsb12', 'price': 'c4ca4238a0b923820dcc509a6f75849b', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 2, 'info': 'd', 'price': '8fa14cdd754f91cc6554c9e71929cce7', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 3, 'info': 'fk', 'price': 'b25ffa68ad761f8578cc61700c0140ed', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 4, 'info': 'hurry', 'price': '46c48bec0d282018b9d167eef7711b2c', 'sdate': 'None', 'edate': 'None', 'id': None}]}

192.168.169.132 - - [05/Jan/2018 19:46:34] "POST /reg HTTP/1.1" 200 -
{"result": "no", "shuju": [{"name": 1, "info": "dsb12", "price": "c4ca4238a0b923820dcc509a6f75849b", "sdate": "None", "edate": "None", "id": null}, {"name": 2, "info": "d", "price": "8fa14cdd754f91cc6554c9e71929cce7", "sdate": "None", "edate": "None", "id": null}, {"name": 3, "info": "fk", "price": "b25ffa68ad761f8578cc61700c0140ed", "sdate": "None", "edate": "None", "id": null}, {"name": 4, "info": "hurry", "price": "46c48bec0d282018b9d167eef7711b2c", "sdate": "None", "edate": "None", "id": null}], "datas": {"code": 1, "data": [{"name": 1, "info": "dsb12", "price": "c4ca4238a0b923820dcc509a6f75849b", "sdate": "None", "edate": "None", "id": null}, {"name": 2, "info": "d", "price": "8fa14cdd754f91cc6554c9e71929cce7", "sdate": "None", "edate": "None", "id": null}, {"name": 3, "info": "fk", "price": "b25ffa68ad761f8578cc61700c0140ed", "sdate": "None", "edate": "None", "id": null}, {"name": 4, "info": "hurry", "price": "46c48bec0d282018b9d167eef7711b2c", "sdate": "None", "edate": "None", "id": null}]}}



最后是 json格式整理 格式很奇葩  这文章没啥意义 就是为了模拟多种传递参数json 和处理json复杂返回的方法


{
    "result": "no",
    "shuju": [
        {
            "name": 1,
            "info": "dsb12",
            "price": "c4ca4238a0b923820dcc509a6f75849b",
            "sdate": "None",
            "edate": "None",
            "id": null
        },
        {
            "name": 2,
            "info": "d",
            "price": "8fa14cdd754f91cc6554c9e71929cce7",
            "sdate": "None",
            "edate": "None",
            "id": null
        },
        {
            "name": 3,
            "info": "fk",
            "price": "b25ffa68ad761f8578cc61700c0140ed",
            "sdate": "None",
            "edate": "None",
            "id": null
        },
        {
            "name": 4,
            "info": "hurry",
            "price": "46c48bec0d282018b9d167eef7711b2c",
            "sdate": "None",
            "edate": "None",
            "id": null
        }
    ],
    "datas": {
        "code": 1,
        "data": [
            {
                "name": 1,
                "info": "dsb12",
                "price": "c4ca4238a0b923820dcc509a6f75849b",
                "sdate": "None",
                "edate": "None",
                "id": null
            },
            {
                "name": 2,
                "info": "d",
                "price": "8fa14cdd754f91cc6554c9e71929cce7",
                "sdate": "None",
                "edate": "None",
                "id": null
            },
            {
                "name": 3,
                "info": "fk",
                "price": "b25ffa68ad761f8578cc61700c0140ed",
                "sdate": "None",
                "edate": "None",
                "id": null
            },
            {
                "name": 4,
                "info": "hurry",
                "price": "46c48bec0d282018b9d167eef7711b2c",
                "sdate": "None",
                "edate": "None",
                "id": null
            }
        ]
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值