下面的代码,仅给大家示例如何组包OpenAPI请求和解析OpenAPI应答。因代码是C++和C语言混合编写的,想用纯C代码实现的人,请参考改写。
http协议的C语言实现,请大家自己去网上找参考代码,这里就不贴了。代码中的Json解析是C++实现,有想用CJson做解析的朋友,请自行改写。
OpenAPI的用户登录:
/* OpenAPI错误码返回信息 */ typedef struct _errorInfo_st { int error; string errorMessage; } errorInfo_st;
/* 用户登录返回信息 */ typedef struct _userLoginResult_st { errorInfo_st errorInfo; string uid; string token; long expireAt; } userLoginResult_st;
userLoginResult_st UserLogin(const char *appID, const char *userName, const char *password) { int responseCode = 0; int answerLen = 0; char *answer = NULL; char httpBody[MAX_BUF_LEN] = { 0 }; char httpHeadCustom[MAX_BUF_LEN] = { 0 }; userLoginResult_st userLoginResult = {};
if (!appID || !userName || !password || !appID[0] || !userName[0] || !password[0]) { userLoginResult.errorInfo.error = ERROR_INVALID_PARAM; userLoginResult.errorInfo.errorMessage = "Invalid param(s)."; return userLoginResult; }
snprintf(httpHeadCustom, sizeof(httpHeadCustom), "Content-Type: application/json\r\n" "X-Gizwits-Application-Id: %s\r\n", appID); snprintf(httpBody, sizeof(httpBody), "{\"username\":\"%s\",\"password\":\"%s\"}", userName, password);
answer = http_request(GWifiConfig::sharedInstance()->GetOpenAPIDomain(), GWifiConfig::sharedInstance()->GetOpenAPIPort(), HTTP_TIMEOUT, HTTP_POST, "/app/login", httpHeadCustom, httpBody, &responseCode, &answerLen); if (answer) { Value jsonRoot = Value(nullValue); Reader jsonReader = Reader();
try { jsonReader.parse(answer, answer + answerLen, jsonRoot);
if('{' == answer[0] && jsonRoot.isObject()) { userLoginResult.errorInfo.error = jsonRoot["error_code"].asInt(); userLoginResult.errorInfo.errorMessage = jsonRoot["error_message"].asString(); userLoginResult.uid = jsonRoot["uid"].asString(); userLoginResult.token = jsonRoot["token"].asString(); userLoginResult.expireAt = jsonRoot["expire_at"].asInt(); } } catch (exception e) { logMsgEx(LV_ERROR, __func__, "Cause parse exception - %s", e.what()); }
free(answer); } else { userLoginResult.errorInfo.error = ERROR_HTTP_FAIL; userLoginResult.errorInfo.errorMessage = "Http request failed: " + (errno ? string(strerror(errno)) : ""); logMsg(LV_WARN, "User %s login failed, responseCode:%d", userName, responseCode); }
//取到才uid跟token才视为成功 if (userLoginResult.uid.empty() || userLoginResult.token.empty()) { if (ERROR_NONE == userLoginResult.errorInfo.error) { userLoginResult.errorInfo.error = ERROR_HTTP_FAIL; userLoginResult.errorInfo.errorMessage = "Http response error format."; } logMsg(LV_ERROR, "User %s login failed, error:%d, errorMessage:%s", userName, userLoginResult.errorInfo.error, userLoginResult.errorInfo.errorMessage.c_str()); } else { logMsg(LV_WARN, "User %s login success, uid:%s, token:%s, expire_at:%ld", userName, userLoginResult.uid.c_str(), userLoginResult.token.c_str(), userLoginResult.expireAt); }
if (userLoginResult.errorInfo.errorMessage.length() && !userLoginResult.errorInfo.error) { userLoginResult.errorInfo.error = ERROR_GENERAL; }
return userLoginResult; }
|