2015年7月16日 星期四

一個簡單的HTTPS GET 程式



用CURL完成一個簡單的HTTPS GET 程式

CURL 一套  open source 命令列工具與函式庫, 以URL語法格式傳送資料

支援協定: DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMTP, SMTPS, Telnet and TFTP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, HTTP/2, cookies, user+password authentication (Basic, Plain, Digest, CRAM-MD5, NTLM, Negotiate and Kerberos)等協定

安裝:  讓libcurl 支援 https 協定, 必須先安裝 OpenSSL 才會有https的支援
  •  (1) 先安裝及下載OpenSSL 函式庫
下載 wget https://www.openssl.org/source/old/0.9.x/openssl-0.9.8y.tar.gz

再進行OpenSSL 函式庫編譯與安裝

tar zxvf openssl-0.9.8y.tar.gz
cd openssl-0.9.8y
make 
make install

  •  安裝libcurl 函式庫

./configure --with-ssl
make 
make install

執行完configure 後, 顯示,目前支擾的協定狀態

目前curl 工具支援的協定
root@raspberrypi:/home/pi/02_gps/curl-7.43.0/src# ./curl -V
curl 7.43.0 (armv7l-unknown-linux-gnueabihf) libcurl/7.43.0 OpenSSL/0.9.8y zlib/1.2.7
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: Largefile NTLM NTLM_WB SSL libz UnixSockets



一個簡單的HTTPS GET 程式


#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>
static char *replace(const char *in, const char *pattern, const char *by);
int main(void)
{
 CURL *curl = curl_easy_init();
 char *new_url;
 char *c_rep=" ";
 char *c_with="+";
 char request[]="https://www.googleapis.com/fusiontables/v2/query?sql=SELECT * from 1fV5mXuKgG5cCck1cAVQX0G7HVTjfdm1SqeYSdmXU&key=AIzaSyDz_-qvtMk7rVWi6NSJMTSv509Df4wTuOg";
 new_url=replace(request,c_rep,c_with);

  fprintf(stderr,"%s\n\n",request);

  if(curl) {
  CURLcode res;
  curl_easy_setopt(curl, CURLOPT_URL,new_url);
  res = curl_easy_perform(curl);
  curl_easy_cleanup(curl);
}

  free(new_url);
  return 0;
}


//replace 函式主要是將 URL 空白字元轉成 + 字元
//sql=SELECT * from  ==> sql=SELECT+*+from
static char *replace(const char *in, const char *pattern, const char *by)
{
    size_t outsize = strlen(in) + 1;
    // TODO maybe avoid reallocing by counting the non-overlapping occurences of pattern
    char *res = malloc(outsize);
    // use this to iterate over the output
    size_t resoffset = 0;

    char *needle;
    while (needle = strstr(in, pattern)) {
        // copy everything up to the pattern
        memcpy(res + resoffset, in, needle - in);
        resoffset += needle - in;
    
        // skip the pattern in the input-string
        in = needle + strlen(pattern);

        // adjust space for replacement
        outsize = outsize - strlen(pattern) + strlen(by);
        res = realloc(res, outsize);

        // copy the pattern
        memcpy(res + resoffset, by, strlen(by));
        resoffset += strlen(by);
    }

    // copy the remaining input
    strcpy(res + resoffset, in);

    return res;
}

程式執行結果




沒有留言 :

張貼留言