开发者

libcurl POST - CURLOPT_READFUNCTION & CURLOPT_WRITEFUNCTION for posting XML

I am attempting to use libcurl to post XML data to a sort-of web service. I开发者_开发百科'm using tinyxml to create an xml document, and I'd like to be able to POST that using curl and parse the XML response with tinyxml as well. I have searched stackoverflow, but none of the existing questions match my scenario.

I can't figure out how to go from a tinyxml printer/std::string to libcurl for POSTing, and then receive the response into memory to be opened by the tinyxml library later.


I've almost gotten the following code to work, but I often receive unhandled exceptions, which are likely due to something with pointers.

typedef struct{
    void *data;
    int body_size;
    int bytes_remaining;
    int bytes_written;
} postdata;


size_t readfunc(void *ptr, size_t size, size_t nmemb, void *stream) {

if(stream) {
    postdata *ud = (postdata*)stream;

if(ud->bytes_remaining) {
    if(ud->body_size > size*nmemb) {
        memcpy(ptr, ud->data+ud->bytes_written, size*nmemb);
        ud->bytes_written+=size+nmemb;
 ud->bytes_remaining = ud->body_size-size*nmemb;
        return size*nmemb;


} else {
     memcpy(ptr, ud->data+ud->bytes_written, ud->bytes_remaining);
            ud->bytes_remaining=0;
  return 0;
        }
}

Thank you for your assistance.


Try this instead:

typedef struct
{ 
    void *data; 
    int body_size; 
    int body_pos; 
} postdata; 


size_t readfunc(void *ptr, size_t size, size_t nmemb, void *stream)
{ 
    if (stream)
    { 
        postdata *ud = (postdata*) stream; 

        int available = (ud->body_size - ud->body_pos);

        if (available > 0)
        { 
            int written = min(size * nmemb, available);
            memcpy(ptr, ((char*)(ud->data)) + ud->body_pos, written); 
            ud->body_pos += written;
            return written; 
        } 
    }

    return 0; 
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜