libcpr / cpr

C++ Requests: Curl for People, a spiritual port of Python Requests.
https://docs.libcpr.org/
Other
6.59k stars 937 forks source link

[Example Request] Dynamic Queries #903

Closed jakemumu closed 1 year ago

jakemumu commented 1 year ago

Hey! I'm just giving this library a shot for the first time and it feels like an oasis in the dessert that is C++ networking.

I did have one question though and I'm struggling to find examples or notes about this in the docs, it seems like a common issue?

I'm trying to use this library to replace another request library, I have an existing code base which wraps this backend, think like Request class which has some of the method common to all http setParams addHeader etc.

This means that I need a way to create CPR requests more dynamically rather than just template constructors -- this seems to be fine with Params since they support .Add() but I'm not seeing where to do that with headers so like instead of:

cpr::Get(Header{"x", "y"}, Header{"a", "b"})

would be more like:

for (const auto& header : headers) {
      headers(header.first, header.second);
}

cpr::Get(headers);

Apologies if this is super simple 0.o. Thank you for all your amazing work on this project!

Is your feature request related to a problem?

NO

Possible Solution

N/A

Alternatives

N/A

Additional Context

N/A

COM8 commented 1 year ago

Hi @jakemumu here is the way I would approach this:

cpr::Session session;

cpr::Header header{{"Header1", "Value1"}};
// Set your initial collection of headers:
session.SetHeader(header);

session.SetUrl("example.com");

cpr::Response response1 = session.Get();

// Update the headers obj in any form:
headers["Header2"] = "Value2";

// Reflect those changes back to the session obj:
session.UpdateHeader(headers);

cpr::Response response2 = session.Get();

// ...

Here is even a test case for that: https://github.com/libcpr/cpr/blob/3020c34ae2b732121f37433e61599c34535e68a8/test/get_tests.cpp#L426-L448

Let me know if this works for you, or if you need anything else.

jakemumu commented 1 year ago

Thank you! Yes that was totally it