tutorial-18-http_client.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright (c) 2023 sogou, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #include <stdio.h>
  14. #include "workflow/WFFacilities.h"
  15. #include "echo_pb.srpc.h"
  16. #include "srpc/http_client.h"
  17. #include "srpc/rpc_types.h"
  18. #include "srpc/rpc_types.h"
  19. #include "srpc/rpc_metrics_filter.h"
  20. #include "srpc/rpc_trace_filter.h"
  21. using namespace srpc;
  22. #define REDIRECT_MAX 5
  23. #define RETRY_MAX 2
  24. srpc::RPCTraceDefault trace_log;
  25. static WFFacilities::WaitGroup wait_group(1);
  26. void callback(WFHttpTask *task)
  27. {
  28. int state = task->get_state();
  29. int error = task->get_error();
  30. fprintf(stderr, "callback. state = %d error = %d\n", state, error);
  31. if (state == WFT_STATE_SUCCESS) // print server response body
  32. {
  33. const void *body;
  34. size_t body_len;
  35. task->get_resp()->get_parsed_body(&body, &body_len);
  36. fwrite(body, 1, body_len, stdout);
  37. fflush(stdout);
  38. fprintf(stderr, "\nfinish print body. body_len = %zu\n", body_len);
  39. }
  40. }
  41. int main()
  42. {
  43. srpc::HttpClient client;
  44. client.add_filter(&trace_log);
  45. WFHttpTask *task = client.create_http_task("http://127.0.0.1:1412",
  46. REDIRECT_MAX,
  47. RETRY_MAX,
  48. callback);
  49. task->start();
  50. wait_group.wait();
  51. return 0;
  52. }