NEON: get/post/put requests

using neon (an HTTP and WebDAV client library, with a C interface)
see how to use GET / PUT / POST in some (not-so-perfect) examples


headers

#include <ne_session.h>
#include <ne_request.h>
#include <ne_utils.h>
#include <ne_uri.h>

GET

int httpResponseReader(void *userdata, const char *buf, size_t len)
{
    string *str = (string *)userdata;
    str->append(buf, len);
    return 0;
}

int do_get(string host)
{
    ne_session *sess;
    ne_request *req;
    string response;

    ne_sock_init();

    sess = ne_session_create("http", host.c_str(), 80);
    ne_set_useragent(sess, "MyAgent/1.0");

    req = ne_request_create(sess, "GET", "/SomeURL/method?with=parameter&value=data");
    // if accepting only 2xx codes, use "ne_accept_2xx"
    ne_add_response_body_reader(req, ne_accept_always, httpResponseReader, &response);

    int result = ne_request_dispatch(req);
    int status = ne_get_status(req)->code;

    ne_request_destroy(req);

    string errorMessage = ne_get_error(sess);
    ne_session_destroy(sess);

    printf("result %d, status %d\n", result, status);
    cout << response << "\n";

    switch (result) {
    case NE_OK:
        break;
    case NE_CONNECT:
        throw ConnectionError(errorMessage);
    case NE_TIMEOUT:
        throw TimeOutError(errorMessage);
    case NE_AUTH:
        throw AuthenticationError(errorMessage);
    default:
        throw AnotherWebError(errorMessage);
    }

    return 0;
}

PUT/POST

int do_put(string data, string host, string url) {
    ne_session *sess;
    ne_request *req;
    string response;

    ne_sock_init();

    sess = ne_session_create("http", host.c_str(), 80);
    ne_set_useragent(sess, "MyUserAgent/1.0");

    req = ne_request_create(sess, "PUT", url.c_str());
    ne_add_request_header(req, "Content-type", "text/xml");
    ne_set_request_body_buffer(req, data.c_str(), data.size());

    int result = ne_request_dispatch(req);
    int status = ne_get_status(req)->code;

    ne_request_destroy(req);

    string errorMessage = ne_get_error(sess);
    ne_session_destroy(sess);
    // just print result & status
    printf("result %d, status %d\n", result, status);

    return 0;
}

note: when using with VC9, have to specify “Ws2_32.lib libneon.lib” as Additional deps in Linker (Project properties)

One thought on “NEON: get/post/put requests

  1. Wow, interesting. What do you intend to use it for – writing you own web crawler? :-)

Leave a Reply

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

6 × 1 =