2016-02-12 146 views
0

我有一個很長的base64編碼文本字符串。大約有1024個字符。從我的Objective C代碼中,我想將它發送到我的PHP腳本,讓它轉儲到日誌中,並返回一個「OK」響應。我試過this cookbook example,但它只有一個上傳和下載的例子(不是兩者結合),它甚至不適用於我的情況。將字符串發送到Web服務器,獲取響應

如果我知道如何,我會願意將它切換到C++解決方案。

的Objective C的客戶端代碼(命令行客戶端)

NSString *sMessage = @"My Long Base64 Encoded Message"; 
NSString *sURL = "http://example.com/request.php"; 
NSURL *oURL = [NSURL URLWithString:sURL]; 

NSData *data = [NSData dataWithBytes:sMessage.UTF8String length:sMessage.length]; 

NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession] 
    dataTaskWithURL:oURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

    NSLog(@"\n\nDATA\n\n%@",data); 
    NSLog(@"\n\nRESPONSE\n\n%@",response); 
    NSLog(@"\n\nERROR\n\n%@",error); 

}]; 

[downloadTask resume]; 

PHP的Web服務器代碼

<?php 

error_reporting(E_ALL); 
ini_set('display_errors','On'); 
$sRaw = file_get_contents('php://input'); 
file_put_contents('TEST.TXT',$sRaw); 
die('OK'); 

回答

0

有使用普通的C++一個更容易的路線。您必須將.m文件轉換爲.mm文件才能混合使用Objective C和C++代碼。

PHP代碼很好,不需要修改。這是我用過的C++示例。它使用STL和捲曲。我在Mac上這樣做,默認情況下,OSX預裝了curl庫。請注意,下面的示例是同步的 - 它阻塞程序執行,直到服務器調用完成。 (我在我的情況需要,本 - 你可能不會)

的C++客戶端代碼(類)

#pragma once 
#include <string> 
#include <sstream> 
#include <iostream> 
#include <curl/curl.h> 

class Webby { 

public: 

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) { 
    std::string buf = std::string(static_cast<char *>(ptr), size * nmemb); 
    std::stringstream *response = static_cast<std::stringstream *>(stream); 
    response->write(buf.c_str(), (std::streamsize)buf.size()); 
    return size * nmemb; 
} 

static std::string sendRawHTTP(std::string sHostURL, std::string &sStringData) { 

    CURL *curl; 
    CURLcode res; 
    curl = curl_easy_init(); 
    if (curl) { 
     std::stringstream response; 
     curl_easy_setopt(curl, CURLOPT_URL, sHostURL.c_str()); 
     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sStringData.c_str()); 
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Webby::write_data); 
     curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); 
     res = curl_easy_perform(curl); 
     curl_easy_cleanup(curl); 
     return response.str(); 
    } 
    return ""; 
} 

}; // end class 
相關問題