C/ObjC中使用CURL判断一个网络文件是否存在

这一次是普通的笔记,注释写得比较清楚,这里就不多废口舌了。记得link上libcurl。

//
//  main.c
//
//  Created by Ryza 15/5/8.
//  Copyright (c) 2015年 Ryza. All rights reserved.
//
 
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <string.h>
 
/**
 *  @brief  判断服务器上某文件是否存在
 *
 *  @param  URL 需要判断的URL
 *
 *  @return HTTP状态码
 */
 

int response(const char * URL) {
    /**
     *  @brief Init CURL
     */
    CURL * curl_fd = curl_easy_init();

    /**
     *  @brief  status code for curl_easy_perform()
     */
    CURLcode code = -1;

    /**
     *  @brief  HTTP response code
     */
    CURLINFO response_code = 0;

    /**
     *  @brief  Use HEAD
     */
    curl_easy_setopt(curl_fd, CURLOPT_NOBODY, 1);

    /**
     *  @brief  Timeout, 3s
     */
    curl_easy_setopt(curl_fd, CURLOPT_TIMEOUT, 3);

    /**
     *  @brief  Set URL
     */
    curl_easy_setopt(curl_fd, CURLOPT_URL, URL);

    /**
     *  @brief  Perform
     */
    code = curl_easy_perform(curl_fd);

    if (code == CURLE_OK) {
        /**
         *  @brief  Get response code
         */
        curl_easy_getinfo(curl_fd, CURLINFO_RESPONSE_CODE, &response_code);
    }

    /**
     *  @brief  Clean up
     */
    curl_easy_cleanup(curl_fd);

    return response_code;
}

int main(int argc, const char * argv[]) {
    for (int i = 1; i < argc; i++) {
        char * URL = (char *) malloc(strlen(argv[i]));
        for (int pos = 0; pos < strlen(argv[i]); pos++) {
            URL[pos] = argv[i][pos];
        }
        printf("[%d] %s\n", response(URL), argv[i]);
        free(URL);
    }
    return 0;
}

GitHub: #/netfile

Leave a Reply

Your email address will not be published. Required fields are marked *

three × 4 =