只需要再JNI的文件夹中新增加cJSON.h和cJSON.cpp文件,同时在Android.mk文件中增加一个cJSON.cpp,然后再命令窗口执行ndk-build.cmd命令生成新的so库,再在login.cpp中Java_com_ldw_hello_BridgeUtils_login方法中处理json相关的方法
login.cpp
//
// Created by Administrator on 2019/10/13.
//
#include "login.h"
#include "cJSON.h"
#include <android/log.h>
/*
* Class: com_ldw_hello_BridgeUtils
* Method: login
* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_com_ldw_hello_BridgeUtils_login
(JNIEnv * env, jobject obj, jstring jni_username, jstring jni_password, jboolean jni_isdriver)
{
const char *username = env->GetStringUTFChars(jni_username, 0);
const char *passwd = env->GetStringUTFChars(jni_password, 0);
const char *isDriver = jni_isdriver == JNI_TRUE?"yes":"no";
char *post_str = NULL;
__android_log_print(ANDROID_LOG_ERROR,TAG,"JNI-login: username = %s, passwd = %s, isDriver = %s",
username, passwd, isDriver);
//封装一个数据协议
/*
====给服务端的协议====
http://ip:port/login [json_data]
{
username: "gailun",
password: "123123",
driver: "yes"
}
*
*
* */
//(1)封装一个json字符串
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "password", passwd);
cJSON_AddStringToObject(root, "driver", isDriver);
post_str = cJSON_Print(root);
__android_log_print(ANDROID_LOG_ERROR,TAG,"JNI-login: post_str = [%s]\n", post_str);
//(2) 想web服务器 发送http请求 其中post数据 json字符串
//(3) 等待服务器的响应
/*
//成功
{
result: "ok",
}
//失败
{
result: "error",
reason: "why...."
}
*
* */
//(4) 解析服务器返回的json字符串
return JNI_TRUE;
}
输出结果如下:
2019-10-14 01:06:43.093 1675-1675/com.ldw.hello E/JNI: JNI-login: username = nihao, passwd = dsaasdada, isDriver = yes
2019-10-14 01:06:43.093 1675-1675/com.ldw.hello E/JNI: JNI-login: post_str = [{
"username": "nihao",
"password": "dsaasdada",
"driver": "yes"
}]
截图如下: