I'm wondering the most simple way to send a request to a API on my server then receive the API's response (json array) wihtout using any libraries. I've tried using libs like cURL & boost without any luck which is the reason i want to stay away from them. I've searched for many days for a answer and have not been able to find anything, which is why i've resorted to coming to the stack overflow community!
-
2Not using a library would be significantly harder than using a library, so use a library. - if you have problems implementing one then they are what you need to address rather than attempting to bake your own json parser which is something you cannot delegate to the operating system.Alex K.– Alex K.2016-03-02 16:23:52 +00:00Commented Mar 2, 2016 at 16:23
-
1C++ doesn't offer support for HTTP connections out of the box. You either dig your way with a library (cURL seems the best way to go) or use the OS primitive for handling socket. You won't like the latter though, considering you are having troubles using a library,Margaret Bloom– Margaret Bloom2016-03-02 16:24:04 +00:00Commented Mar 2, 2016 at 16:24
-
It all depends on what platform you're targeting but I would say that writing HTTP code using bare sockets/apis is much more of a headache than trying to figure out how a library works. I suggest using the C++ Rest Sdk.Mohamad Elghawi– Mohamad Elghawi2016-03-02 16:28:09 +00:00Commented Mar 2, 2016 at 16:28
-
@MargaretBloom when i download cURL i get ALOT of files, i cant seem to find the .lib file withing the cURL .zip :/JeffCoderr– JeffCoderr2016-03-02 16:32:55 +00:00Commented Mar 2, 2016 at 16:32
1 Answer
Even though the question is about not using a library I 'am taking this opportunity to show how easy it is to use a library than the user thinks.
Its better to use pre-built libraries and stop reinventing the wheel. You can use curlcpp library. Its a wrapper for libcurl. Using this library HTTP requests can be made easily. Learning curve is also less and it provides C++ style access which makes it more comfortable to work with.
The following code is taken from their gitHub page - https://github.com/JosephP91/curlcpp
It makes a simple GET request to Google and retrieves the HTML response. You can use this example to hit apis too.
#include "curl_easy.h"
#include "curl_exception.h"
using curl::curl_easy;
using curl::curl_easy_exception;
using curl::curlcpp_traceback;
int main(int argc, const char **argv) {
curl_easy easy;
// Add some option to the curl_easy object.
easy.add<CURLOPT_URL>("http://www.google.it");
easy.add<CURLOPT_FOLLOWLOCATION>(1L);
try {
// Execute the request.
easy.perform();
} catch (curl_easy_exception error) {
// If you want to get the entire error stack we can do:
curlcpp_traceback errors = error.get_traceback();
// Otherwise we could print the stack like this:
error.print_traceback();
// Note that the printing the stack will erase it
}
return 0;
}