CURL: Save response to string
Jonathan M Davis
jmdavisProg at gmx.com
Sat Jun 30 14:55:50 PDT 2012
On Saturday, June 30, 2012 21:49:51 Nrgyzer wrote:
> Hi guys,
>
> I know... there's a lib for curl but I'm using an old CURL-binding for D...
> I've the following problem: I'm sending my login data to a web page and I
> want store the response of curl_easy_perform() in a string. So I'm using
> the following few lines to do that:
>
> string temp;
>
> size_t callback(char* ptr, size_t size, size_t, nmemb, string* stream) {
> temp ~= *ptr;
> // or: How can I append ptr to my stream?
> // When I use '*stream ~= cast(char) ptr;' I get an memory violation...
> }
>
> void main() {
> CURL* curl = curl_easy_init();
>
> curl_httppost* post;
>
> curl_formadd(&post, &last, CURLFORM_COPYNAME, toStringz("username"),
> CURLFORM_COPYCONTENTS, toStringz("username"), CURLFORM_END);
> curl_formadd(&post, &last, CURLFORM_COPYNAME, toStringz("password"),
> CURLFORM_COPYCONTENTS, toStringz("password"), CURLFORM_END);
> curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
> curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &callback);
> curl_easy_setopt(curl, CURLOPT_WRITEDATA, &temp);
> curl_easy_setopt(curl, CURLOPT_URL,
> toStringz("https://myURL.tld/login.php")); curl_easy_perform(curl);
> writeln(temp);
> }
>
> But when I run the code, temp is completely empty... does anyone know how to
> fix that or what I'm doing wrong?
>
> Thanks for all suggestions!
cast(char)ptr is casting a pointer to a char. That's not what you want at all.
Assuming that size is the length of the string that ptr points to (not
including a terminating '\0'), then do
temp ~= ptr[0 .. size];
If size _does_ include a terminating '\0', then do
temp ~= ptr[0 .. size - 1];
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list