http_client_test.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "requests.h"
  2. #include "hthread.h" // import hv_gettid
  3. static void test_http_async_client(int* finished) {
  4. printf("test_http_async_client request thread tid=%ld\n", hv_gettid());
  5. HttpRequestPtr req(new HttpRequest);
  6. req->method = HTTP_POST;
  7. req->url = "127.0.0.1:8080/echo";
  8. req->headers["Connection"] = "keep-alive";
  9. req->body = "this is an async request.";
  10. req->timeout = 10;
  11. http_client_send_async(req, [finished](const HttpResponsePtr& resp) {
  12. printf("test_http_async_client response thread tid=%ld\n", hv_gettid());
  13. if (resp == NULL) {
  14. printf("request failed!\n");
  15. } else {
  16. printf("%d %s\r\n", resp->status_code, resp->status_message());
  17. printf("%s\n", resp->body.c_str());
  18. }
  19. *finished = 1;
  20. });
  21. }
  22. static void test_http_sync_client() {
  23. // auto resp = requests::get("http://www.example.com");
  24. //
  25. // make clean && make WITH_OPENSSL=yes
  26. // auto resp = requests::get("https://www.baidu.com");
  27. auto resp = requests::get("http://127.0.0.1:8080/ping");
  28. if (resp == NULL) {
  29. printf("request failed!\n");
  30. } else {
  31. printf("%d %s\r\n", resp->status_code, resp->status_message());
  32. printf("%s\n", resp->body.c_str());
  33. }
  34. hv::Json jroot;
  35. jroot["user"] = "admin";
  36. http_headers headers;
  37. headers["Content-Type"] = "application/json";
  38. resp = requests::post("127.0.0.1:8080/echo", jroot.dump(), headers);
  39. if (resp == NULL) {
  40. printf("request failed!\n");
  41. } else {
  42. printf("%d %s\r\n", resp->status_code, resp->status_message());
  43. printf("%s\n", resp->body.c_str());
  44. }
  45. }
  46. int main() {
  47. int finished = 0;
  48. int cnt = 1;
  49. for (int i = 0; i < cnt; ++i) {
  50. test_http_async_client(&finished);
  51. test_http_sync_client();
  52. hv_delay(1000);
  53. }
  54. // demo wait async ResponseCallback
  55. while (!finished) {
  56. hv_delay(100);
  57. }
  58. printf("finished!\n");
  59. return 0;
  60. }