Android:libcurl客户端发送https请求

libcurl客户端发送https请求
客户端只需要将url由http变成https。

如果服务端不是CA认证,那么会请求失败,需要加上两行代码,不是CA认证也正常访问

curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);

详细代码如下:

bool login(char *username, char passwd)
{
// packet username and password to json
/

{
username: “aaa”,
password: “bbb”,
logintype: 1
}
/
cJSON
root = cJSON_CreateObject();

cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "password", passwd);
cJSON_AddNumberToObject(root, "logintype", 1);

char *json_str = cJSON_Print(root);
cJSON_Delete(root);

//curl
CURLcode curl_ret;
CURL *curl = curl_easy_init();
curl_response_data_t res_data;
const char *uri = "https://192.168.2.113:8080/login";

//http://127.0.0.1:8080/login
curl_easy_setopt(curl, CURLOPT_URL, uri);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_str);

//取消SSL非法认证错误
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_login_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &res_data);

curl_ret = curl_easy_perform(curl);
if (curl_ret != CURLE_OK) {
    __android_log_print(ANDROID_LOG_ERROR, "login", "curl perform error, ret=%d\n", curl_ret);
    return false;
}
curl_easy_cleanup(curl);

res_data.data[res_data.datalen] = '\0';
free(json_str);


//login end, server response json data in res_data
//parse json

/*
   //成功
   {
        result: "ok",
        sessionid: "xxxxxxxx"
    }
    //失败
    {
        result: "error",
        reason: "why...."
    }
*/

root = cJSON_Parse(res_data.data);
cJSON* result = cJSON_GetObjectItem(root, "result");
if (result && (strcmp(result->valuestring, "ok") == 0) ) {
    //succ!
    cJSON* sessionid = cJSON_GetObjectItem(root, "sessionid");

    __android_log_print(ANDROID_LOG_ERROR, "login", "login succ, sid=%s\n", sessionid->valuestring);

    return true;
}
else {
    //fail
    cJSON *reason = cJSON_GetObjectItem(root, "reason") ;
    if (reason) {
        __android_log_print(ANDROID_LOG_ERROR, "login", "login fail, reason=%s\n", reason->string);
    }
    else {
        __android_log_print(ANDROID_LOG_ERROR, "login", "login fail, unknow reason\n");
    }
}



cJSON_Delete(root);



return true;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值