1

It's already been covered how to get the response code in this question:

Http status code with libcurl?

And how to receive data with a callback here:

libcurl HTTPS POST data send?

My question is about receiving or checking the status inside the callback.

Points to consider:

  • The callback does not receive the CURL handle by default. That means I don't know if it's safe to call functions like curl_easy_getinfo() inside it, if I pass the CURL handle myself.

  • I want the information inside the callback, so it can decide how to operate based on whether the HTTP status code is 200, or something else.

  • I can't just check after the call to curl_easy_perform() because that would defeat the purpose of my callback.

  • The documentation doesn't say anything about the behaviour of calling curl_easy_*() functions inside the callback, so at a first guess I think it's unsafe to do.

Do I have any options to do this?

EDIT: The book Everything Curl by Daniel Steinberg says

These information values are designed to be provided after the transfer is completed.

And so I will not be "accepting" my own answer.

Johann Oskarsson
  • 776
  • 6
  • 15
  • I think, you can provide the CURL handle inside the userdata argument (either directly or, if you need to pass more data, inside a struct). Then you can call curl_easy_getinfo() inside your callback using this handle. This should be safe. – Ctx Oct 24 '17 at 07:52
  • AFAIK, it is safe to call most curl functions, except `perform`, from within the callback (and `perform` is only unsafe because of possibility of recursion). If the status code hasn't been received yet, the function might return error or -1, but nothing bad should happen. – user1643723 Oct 24 '17 at 08:35

1 Answers1

2

Yes, Ctk and user1643723 are correct.

With

curl_easy_setopt( handle, CURLOPT_WRITEDATA, handle );

before curl_easy_perform() and the following in my callback,

long code = -1;
curl_easy_getinfo( handle, CURLINFO_RESPONSE_CODE, &code );
/* superfluous printf() */
printf( "HTTP Response Code: %ld\n", code );

I have the HTTP status inside it.

I would be more comfortable if the libcurl documentation explicitly said this was OK.

Johann Oskarsson
  • 776
  • 6
  • 15